Vuelidate: validate form with sub components

强颜欢笑 提交于 2019-12-01 20:08:12
Harshal Patil

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.

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