我有一个有两个道具的组件,但为了使它们有效,只应提供其中一个。
示例:
// either `email` or `phone` should be passed (but not both)
props: {
email: {
type: String,
required: true
},
phone: {
type: String,
required: true
},
}
Run Code Online (Sandbox Code Playgroud)
有没有办法验证基于彼此的道具?
我想把它放在生命周期钩子的某个地方,但感觉不合适。
我认为生命周期钩子不是放置验证逻辑的好地方,因为钩子只被调用一次,因此如果 prop 值在未来发生变化,那么你将不会再次获得相同的验证。相反,您可以尝试在 Vue 实例的$props对象上使用 set a 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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
在这里,我添加了一个基本的验证逻辑,您可以根据您的要求对其进行更新。
在created您的组件实例的钩子中,您可以访问this.$props(它将是一个数组或对象[在您的案例对象中],包含传递给该组件的所有道具)。然后您可以检查该对象中是否存在属性,如果不存在,您可以抛出错误或显示通知(无论您想要什么)。
...
created() {
if(this.$props.email == null && this.$props.phone == null) {
throw Error('You have to pass at least one prop');
}
},
...
Run Code Online (Sandbox Code Playgroud)
您还必须记住删除此required: true标志:
props: {
email: {
type: String
},
phone: {
type: String
}
},
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
619 次 |
| 最近记录: |