我想在我的一个组件中接受对象和null(即使对象为typeof null === 'object'
,对象也为Vue.js checks for null values),但是我想使undefined
值的验证失败。
我尝试了什么(使用 vue-property-decorator
)
@Prop({ required: true, type: Object, validator: v => typeof v === 'object' })
@Prop({ required: true, validator: v => typeof v === 'object' })
// I got an error:
//> Expected Object, got Null.
@Prop({ validator: v => typeof v === 'object' })
// Let's undefined through, so when I don't specify the prop, I get no warnings
// making the validator useless for my purposes
我如何接受对象(包括
null
)作为属性,同时确保使用我的组件的开发人员收到警告(如果值是undefined
(在省略prop时发生))? 最佳答案
从documentation on props validation
检查源代码后,基本类型使用以下正则表达式定义。
因此type: Object,
不正确。您可以删除type
属性检查,保留required
和自定义validator
检查。
@Prop({
required: true,
validator: v => typeof v === 'object',
})
如果只想确保prop至少设置为null,则可以删除
required
检查并添加一个简单的default: null
。@Prop({
type: Object,
default: null,
})
类型检查中不会使用对Vue
isObject
utils的引用。它使用 isPlainObject
。通过执行以下操作可以区分
null
:Object.prototype.toString.call(null)
// => "[object Null]"