Vue js - 将prop定义为特定类型

Sto*_*orm 2 javascript vue.js vue-component vuejs2

我正在构建一个vuejs组件,它接受一个名为idFieldType的prop

现在我希望这个prop只接受Number TypeString Type

所以我写了如下

idFieldType: {
    Type: Function,
    default: function() {
        return Number;
    },
    validator: function() {
         if(value == String || value == Number) {
               return true;
         }

         return false;    
    }
}
Run Code Online (Sandbox Code Playgroud)

我也尝试将类型替换为Object.

我的问题是如何编写一个只接受特定类型的道具?

Nar*_*k-T 7

Vue.JS内置道具验证,你可以设置类型,是否需要,默认值...例如:

Vue.component('example', {
  props: {
    // basic type check (`null` means accept any type)
    propA: Number,
    // multiple possible types
    propB: [String, Number],
    // a required string
    propC: {
      type: String,
      required: true
    },
    // a number with default value
    propD: {
      type: Number,
      default: 100
    },
    // object/array defaults should be returned from a
    // factory function
    propE: {
      type: Object,
      default: function () {
        return { message: 'hello' }
      }
    },
    // custom validator function
    propF: {
      validator: function (value) {
        return value > 10
      }
    }
  }
})
Run Code Online (Sandbox Code Playgroud)

请注意,Vue.js也接受多种可能的类型propB: [String, Number],,这就是您所需要的.您可以在官方维基中阅读更多相关信息