我正在构建一个 vuejs 组件,它接受名为 idFieldType
的 Prop现在我希望这个 Prop 只接受数字类型或字符串类型
于是我就这样写了
idFieldType: {
Type: Function,
default: function() {
return Number;
},
validator: function() {
if(value == String || value == Number) {
return true;
}
return false;
}
}
我还尝试将类型替换为 Object。
我的问题是如何编写一个只接受特定类型的 Prop ?
最佳答案
Vue.JS 内置了 props 验证,你可以设置类型,是否需要,默认值... 例如:
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
}
}
}
})
请注意,Vue.js 还接受多种可能的类型 propB: [String, Number],
,这就是您所需要的。
您可以在 official wiki 中阅读更多相关信息
关于javascript - Vue js - 将 Prop 定义为特定类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45520700/