我有一个包含两个道具的组件,但为了使其有效,只能提供其中的一个一个。
示例:
// either `email` or `phone` should be passed (but not both)
props: {
email: {
type: String,
required: true
},
phone: {
type: String,
required: true
},
}
有没有一种方法可以相互验证道具?
我正在考虑将其放在生命周期挂钩中的某个位置,但是感觉不合适。
答案 0 :(得分:2)
我认为生命周期挂钩不是放置验证逻辑的好地方,因为挂钩仅被调用一次,因此如果prop值将来发生更改,那么您将不会再次获得相同的验证。相反,您可以尝试在Vue实例的$props
对象上使用set watcher来监视对props值的任何更改,并在每次更改时触发验证,例如:
props: {
email: String,
phone: String
},
methods: {
validateProps() {
// Here you can access both props and add your validation logic
if(!this.email && !this.phone){
console.error('Please add either email or phone props');
}
}
},
watch: {
$props: {
immediate: true,
handler() {
this.validateProps();
}
}
}
在这里,我添加了基本的验证逻辑,您可以根据需要对其进行更新。
答案 1 :(得分:1)
我建议使用计算所得的属性。
<template>
<div>{{ emailOrPhone }}</div>
</template>
<script>
export default {
name: "HelloWorld",
props: {
email: {
type: String
},
phone: {
type: String
}
},
computed: {
emailOrPhone() {
return this.email || this.phone || 'warning: email or phone required';
}
}
};
</script>
答案 2 :(得分:1)
在组件实例的created
钩子中,您可以访问this.$props
(它将是一个数组或对象(在您的情况下为对象),包含传递给该组件的所有props)。然后,您可以检查此对象中是否存在属性,否则可以引发错误或显示通知(无论您想要什么)。
...
created() {
if(this.$props.email == null && this.$props.phone == null) {
throw Error('You have to pass at least one prop');
}
},
...
您还必须记住删除此required: true
标志:
props: {
email: {
type: String
},
phone: {
type: String
}
},