简体   繁体   English

有没有办法在 Vue 中验证多个道具?

[英]Is there a way to validate multiple props in Vue?

I have a component that has two props, but in order to be valid only one of them should be provided.我有一个包含两个道具的组件,但为了有效,应该只提供其中一个

Example :示例

    // either `email` or `phone` should be passed (but not both)
    props: {
        email: {
            type: String,
            required: true
        },

        phone: {
            type: String,
            required: true
        },
    }

Is there a way to validate props based on each other?有没有办法基于彼此验证道具?

I'm thinking of putting this somewhere in a lifecycle hook, but it feels out of place.我想把它放在生命周期钩子的某个地方,但感觉不合适。

I think lifecycle hook would not be a good place to put the validation logic, as the hooks are called only once and thus if the prop values changes in future, then you will not get the same validations again.我认为生命周期钩子不是放置验证逻辑的好地方,因为钩子只被调用一次,因此如果将来道具值发生变化,那么您将不会再次获得相同的验证。 Instead, you can try to use set a watcher on the Vue instance's $props object to watch for any changes to the props value in future and trigger validation on each change like:相反,您可以尝试在 Vue 实例的$props object 上设置一个观察程序来观察将来对 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();
    }
  }
}

Here, I have added a basic validation logic, you can update it as per your requirements.在这里,我添加了一个基本的验证逻辑,您可以根据需要对其进行更新。

In created hook of your component instance you can access this.$props (it will be an array or object [in your case object], containing all props passed to this component).在您的组件实例的created钩子中,您可以访问this.$props (它将是一个数组或 object [在您的案例对象中],包含传递给该组件的所有道具)。 Then you can check is property existing in this object if not you can throw an error or show notification (whatever you want).然后您可以检查此 object 中是否存在属性,如果没有,您可以抛出错误或显示通知(无论您想要什么)。

...
created() {
 if(this.$props.email == null && this.$props.phone == null) {
  throw Error('You have to pass at least one prop');
 }
},
...

You also have to remember to remove this required: true flag:您还必须记住删除此required: true标志:

  props: {
    email: {
      type: String
    },
    phone: {
      type: String
    }
  },

I would suggest using a computed property.我建议使用计算属性。

<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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM