我想在我的一个组件中接受对象和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]"

10-01 04:33
查看更多