vue + element + Promise 实现点击保存同时校验两个或者多个form表单

场景:在开发中,经常会有大的表单界面,点击保存后界面上的表单都要做校验

export default{
    data(){
        resultArr:[],//接受验证返回结果数组
        formArr:['form1','form2','form3','form4'],//存放表单ref数组
    },
    methods:{
        //封装验证函数
        checkForm(formName){
            let _self=this;
            _self.resultArr = []
            let result = new Promise(function(resolve, reject) {
            _self.$refs[formName].validate((valid) => {
                if (valid) {
                    resolve();
                } else { reject() }
                })
            })
            _self.resultArr.push(result) //push 得到promise的结果
        },
        submit(){
            let _self=this;
            _self.formArr.forEach(item => { //根据表单的ref校验
                _self.checkForm(item)
            })
           //resultArr数组的值必须是promise对象才能使用Promise.all,在checkForm做了这一步
            Promise.all(_self.resultArr).then(function() { //都通过了
              alert('所有表单验证通过')
              // 该区域使用this无效,promise内面的this表示局部,并不代表VueComponet实例
            }).catch(function() {
                console.log("err");
            });
        }
    }
}

猜你喜欢

转载自blog.csdn.net/m0_66722601/article/details/128255266