多表单如何优雅的进行规则校验

323 阅读1分钟

常见写法

  methods: {
    submit() {
     // 标记所有表单是否通过校验的变量
     let isValid = true
     
     // 遍历表单数组,依次对每个表单进行校验
     this.formRefs.forEach(ref => {
     	this.$refs[ref].validate(valid => {
     		if (!valid) {
     			isValid = false
     		}
     	})
     }}
     
     // 如果所有表单都校验通过,执行提交操作
     if (isValid) {
     	// 执行提交操作
     }
    }

问题1:如果一个vue页面中出现两个以上的from表单应该如何简洁的进行校验

解决问题1:

  • 通过给每个<form>组件添加ref属性,然后通过this.$refs.xxx找到表单组件
  • 把所有表单组件的实例放到一个数组当中,然后通过Promise.all方法对表单进行批量校验
    mounted() {
        this.forms = [this.$refs.form1Ref, this.$refs.form2Ref]
    },
    methods: {
        onSubmit(){
            //批量校验,通过Promise.all
            Promise.all(this.forms.map(t=>t.validate())).then(res=>{
                console.log(res);
                console.log('成功');
            }).catch(err=>{
                console.log(err);
                console.log('失败');
            })

    }

问题2:如果一个页面中有较多子组件,并且子组件里面含有from表单,如何优雅校验

解决问题2:

  • 通过组件的$children属性获取当前组件所有子组件,然后判断它的options.name是否为Form判断它是否是表单组件
  • 通过递归的方式按照上述方式,得到所有的表单组件实例
  • 把所有表单组件的实例放到一个数组当中,然后通过Promise.all方法对表单进行批量校验
    data(){
        return {
            forms: []//表单组件集合
        }
    },
    mounted() {
        //通过递归的方式在组件树中找到表单组件
        this.findFormComponent(this.$children)
    },
    methods: {
        //递归方法
        findFormComponent(children) {
            children.forEach((item) => {
                if (item.$options.name === 'Form') {
                    this.forms.push(item)
                } else {
                    item.$children && this.findFormComponent(item.$children)
                }
            })
        },
        onSubmit(){
            //批量校验,通过Promise.all
            Promise.all(this.forms.map(t=>t.validate())).then(res=>{
                console.log(res);
                console.log('成功');
            }).catch(err=>{
                console.log(err);
                console.log('失败');
            })

        }
    }