Vue2-props--required

284 阅读1分钟

required

props 属性中的 required 选项是用来指定该属性是否是必需的。如果将 required 设置为 true,则父组件在使用该子组件时必须传入该属性,否则会收到警告或错误。

Tips:在 Vue 2 中,如果一个 requiredprop 没有被传入,Vue 会在开发环境下给出一个警告,但不会导致程序崩溃。

// 警告:[Vue warn]: Missing required prop: "requiredProp"
new Vue({
  el: "#app",
  data: {
    requiredData: "必要的参数",
  },
  // template: `<my-component :required-prop="requiredData"></my-component>`,
  template: `<my-component></my-component>`,
  components: {
    "my-component": {
      props: {
        requiredProp: {
          required: true,
        },
      },
      template: `<div>requiredProp={{ requiredProp }}</div>`,
    },
  },
});

注意:在 Vue 2 中,propsrequired 选项是不能够动态决定的。一旦组件定义时将某个 prop 声明为 required: true,那么在使用该组件时,父组件必须传入该 prop。这是在组件创建阶段就确定的,并不能在运行时动态改变。