是否可以在Vue中使props有条件,例如prop2依赖于prop1的值?

flseospp  于 2023-04-12  发布在  Vue.js
关注(0)|答案(2)|浏览(120)

我有一个用例,我需要向自定义组件传递特定的错误消息。当且仅当某个prop设置为true时。但我怀疑this.required在props中可用,因为它尚未初始化。

//custom component
props: {
  required: {
    type: Boolean,
    default: false
  },
  requiredErrorMsg: {
    type: String,
    default: '',
    required: this.required
  }
}

Vue(或eslint?)应该抛出一个警告或错误,如果prop丢失,这取决于required是否设置为true。

<Custom :required="true" /> //missing prop error
<Custom :required="true" required-error-msg="this is an error"/> //no issues

当前使用:
新版本2.3.4
eslint v5.0.1

xmakbtuz

xmakbtuz1#

当一个必需的 prop 丢失时,Vue本身从来不会真正“抛出”错误。Vue只会发出[Vue warn]documentation中并没有提到这一点。为了证明这一点,如果你运行下面的代码片段,你可以看到它仍然可以渲染:

Vue.component('custom-component', {
  template: `
    <div>
      required:<br>
      {{ required }}
      <br><br>
      requiredErrorMessage:<br>
      {{ requiredErrorMessage }}
    </div>
  `,
  props: {
    required: {
      type: Boolean,
      default: false
    },
    requiredErrorMessage: {
      type: String,
      default: '',
      required: true  // <-- Explicitly set to true
    }
  }
});

new Vue({
  el: '#app'
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <custom-component
    :required="true"
  />
</div>

如果你想让它真正抛出(停止执行),你需要使用computed属性显式地将它设置为throw。如果你在 used computed属性中显式地使用throw运行下面的代码片段,你应该看到它根本不会呈现:

Vue.component('custom-component', {
  template: `
    <div>
      required:<br>
      {{ required }}
      <br><br>
      requiredErrorMessage:<br>
      {{ errorMessage }}
    </div>
  `,
  props: {
    required: {
      type: Boolean,
      default: false
    },
    requiredErrorMessage: {
      type: String,
      default: '',
    }
  },
  computed: {
    errorMessage(){
      if (this.required === true && !this.requiredErrorMessage)
        // Explicitly call `throw` when required conditions are not met
        throw new Error('Missing prop error.');
        
      return this.requiredErrorMessage;
    }
  }
});

new Vue({
  el: '#app'
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <custom-component
    :required="true"
  />
</div>
jvidinwx

jvidinwx2#

当然可以... VUE 3

props: {
    prop1: {
        type: Boolean,
        default: false
    },
    prop2: {
        type: String,
        default: (propsListWithValues) => {
            if (propsListWithValues.prop1 == true) {
                return "prop2 now have conditional text by prop1"
            }
        }
    }
}

相关问题