Vuelidate: validate form with sub components

我只是一个虾纸丫 提交于 2019-12-01 19:05:27

问题


How to work with validations of nested components inside a parent component with Vuelidate? I would like to change parentForm.$invalid if inputs in subcomponents are valid or not.

Parent:

<parent-component>
  </child-component-1>
  </child-component-2>
</parent-component>

validations: {
  parent: WHAT HERE?
}

Child-1

<child-component-1>
  </some-input>
</child-component-1>

data() {
  return {
    someInput: ""
  };
},

validations: {
  someInput: required
}

Child-2

<child-component-2>
  </some-input>
</child-component-2>

data() {
  return {
    someInput: ""
  };
},

validations: {
  someInput: required
}

回答1:


The simplest way to get started with vuelidate for sub-components/form is to use Vue.js dependency injection mechanism provided by provide/inject pair. The $v instance created in parent component can be shared with children component.

As you more fine tune it, you can use Vuelidate data-nesting and only pass a subset of $v to your subcomponents. This is a roughly similar approach to how Angular does with nested Forms. It would look something like:

export default {
    data() {
        return {
            form1: {
                nestedA: '',
                nestedB: ''
            } /* Remaining fields */
        }
    },
    validations: {
        form1: {
            nestedA: {
                required
            },
            nestedB: {
                required
            }
        },

        form2: {
            nestedA: {
                required
            },
            nestedB: {
                required
            }
        }
    }
}

Alternately, you can declare independent instances of $v for each component. In your case, you will have one for parent and two for children. When you hit the submit button, get the reference of child component using $refs and check if nested form within the child component is valid or not.




回答2:


I might not be an expert in Vue. If you have declared validations in the child component and you want to access it from the parent component you can use reference the child component from parent component in this way.

In parent component it would be like

<template>
<my-child ref="mychild"> </my-child>
</template>

You can access the validations declared in my-child component which is $v object using

this.$refs.mychild.$v

and then you can use validations of child component in parent components with such ease. Hope this will make the job much easier then using complex ways and it worked for me.



来源:https://stackoverflow.com/questions/54344033/vuelidate-validate-form-with-sub-components

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