如何在 VueJS 中映射具有计算属性的嵌套 Vuelidate 验证对象?

How to map a nested Vuelidate validation object with computed properties in VueJS?

我有一个包含多个表单的选项卡容器。所有表单中的某些字段都有一些复杂的逻辑,我不想在每个表单上重复这些逻辑,因此我创建了一个用于所有表单的自定义组件。我正在尝试使用 Vuelidate 来验证我的所有表单,但由于这些字段名称相同,并且当然具有相同的验证逻辑,因此 Vuelidate 验证对象在所有表单中都是相同的,这意味着,如果我填写 email 表单 A 中的字段,那么具有相同字段的所有表单也将正确验证,即使其余表单根本没有填写。

我试图将我的验证包装在一个名为表单的对象中,这似乎正确地分离了所有验证逻辑,但是,我在那里有其他设置阻止我使用 data 属性,我使用computed 属性代替。据我所知,验证对象必须匹配我们访问字段数据的方式,例如,data() { formA: { email } } 将匹配验证对象 validations: { formA: { email } },问题是,因为我没有使用 data 属性,我不知道如何映射计算属性。

这是我的:

  export default {
    components: { PhoneField, TopNote, SubmitButton, NameFieldsGroup, EmailField },
    validations: {
      formA: {
        firstName: { required },
        lastName: { required },
        email: {
          required,
          email
        },
        phone: {
          required,
          length: minLength(10)
        }
      }
    },
    created() {
      this.$store.commit('setFormValidation', this.$v);
    },
    data() {
      return {}
    },
    computed: {
      firstName: function() {
        return this.$store.getters.formState.firstName;
      },
      lastName: function() {
        return this.$store.getters.formState.lastName;
      },
      email: function() {
        return this.$store.getters.formState.email;
      },
      phone: function() {
        return this.$store.getters.formState.phone;
      }
    }
  };

这几天我一直在胡思乱想,但想不通。有人可以为此提出解决方案吗?

想通了。不确定为什么会起作用,但现在可以了。解决方法是像这样使用 Vuex 的 mapState

import { mapState } from 'vuex';

export default {
    components: { PhoneField, TopNote, SubmitButton, NameFieldsGroup, EmailField },
    validations: {
      formA: {
        firstName: { required },
        lastName: { required },
        email: {
          required,
          email
        },
        phone: {
          required,
          length: minLength(10)
        }
      }
    },
    created() {
      this.$store.commit('setFormValidation', this.$v);
    },
    data() {
      return {}
    },
    computed: {
      ...mapState(['formA']),
      firstName: function() {
        return this.$store.getters.formState.firstName;
      },
      lastName: function() {
        return this.$store.getters.formState.lastName;
      },
      email: function() {
        return this.$store.getters.formState.email;
      },
      phone: function() {
        return this.$store.getters.formState.phone;
      }
    }
  };