繁体   English   中英

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

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

我有一个包含两个道具的组件,但为了有效,应该只提供其中一个

示例

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

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

有没有办法基于彼此验证道具?

我想把它放在生命周期钩子的某个地方,但感觉不合适。

我认为生命周期钩子不是放置验证逻辑的好地方,因为钩子只被调用一次,因此如果将来道具值发生变化,那么您将不会再次获得相同的验证。 相反,您可以尝试在 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();
    }
  }
}

在这里,我添加了一个基本的验证逻辑,您可以根据需要对其进行更新。

在您的组件实例的created钩子中,您可以访问this.$props (它将是一个数组或 object [在您的案例对象中],包含传递给该组件的所有道具)。 然后您可以检查此 object 中是否存在属性,如果没有,您可以抛出错误或显示通知(无论您想要什么)。

...
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
    }
  },

我建议使用计算属性。

<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