Validate form input fields in child component from a parent component with Vuelidate

送分小仙女□ 提交于 2019-12-08 06:19:31

问题


I am new to Vue Js and Vuelidate. Just tried to validate form input fields from a parent component like here: https://github.com/monterail/vuelidate/issues/333

Child component in the parent:

<contact-list ref="contactList" :contacts="contacts" @primaryChanged="setPrimary" @remove="removeContact" @ready="isReady => readyToSubmit = isReady"/>

The method in the child:

computed: {
    ready() {
        return !this.$v.email.$invalid;
    }
},
watch: {
    ready(val) {
        this.$emit('ready', val);
    }
},

methods: {
    touch() {
        this.$v.email.$touch();
    }
}

I'm calling the touch() method from the parent like so:

submit() {
            this.$refs.contactList.touch();
        },

But I get this error:

Error in event handler for "click": "TypeError: this.$refs.contactList.touch is not a function".

Any ideas? Thanks.


回答1:


I have found another solution for this validation, it's very simple. Child component in the parent:

<contact-list ref="customerContacts" :contacts="customer.contacts" />

Validations in child component:

:validator="$v.model.$each[index].name
...
validations: {
    model: {
        required,
        $each: {
            name: {
                required
            },
            email: {
                required,
                email
            },
            phone: {
                required
            }
        }

    }

}

And on submit in the parent:

async onSubmit() {
            if(this.$refs.customerContacts.valid())
...



回答2:


Had a similar issue trying to validate child components during a form submission on the parent component. My child components are only one level deep so if you have deeper nesting this way may not work or you have to check recursively or something. There are probably better ways to check but this worked for me. Good luck.

// parent component
  methods: {
    onSave() {
      let formIsInvalid = this.$children.some(comp => {
        if (comp.$v) { // make sure the child has a validations prop
          return comp.$v.$invalid
        }
      })

      if (!formIsInvalid) {          
        // submit data
      }          
      else {
        // handle invalid form
      }
   }


来源:https://stackoverflow.com/questions/53628450/validate-form-input-fields-in-child-component-from-a-parent-component-with-vueli

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!