如何优雅的校验v-for中的form

2,103 阅读1分钟

1、前言

本文已参与「新人创作礼」活动,一起开启掘金创作之路。在web开发中,前端用以收集、校验、提交数据等场景都会用到form表单,form表单最便捷之处在于可以非常方便的对用户(客户)输入值做特定的校验,例如:非法输入,必填项缺省等。对整个表单进行校验的方法validate,往往接受一个回调参数或者不传参返回一个promise来等待验证结果,再做后续处理。今天我们讨论的是vue中v-for中生成多个form表单怎么优雅的校验。

2、实现效果

b2eae5b9614108213b7aa89088895a56.png

Tips:
1、整体外层一个form,内层多个form组成。
2、点击add card 会在label3中增加一个card即增加一个from,每个card点击X删除一个卡片即删除一个form。

3、View层

<div      
    v-for="(item, index) in actionData"      
    :key="item"      class="form-wrapper"  
>    
    <el-form        
        ref="actionForm"        
        :model="item"        
        label-width="68px"        
        class="item-form"    
    >    
    </el-form>
</div>

4、数据层

4.1、 data

actionData: [{ id: 'no1', name: '前端秀'}];

4.2、methods

/* add */
const add = () => {  actionData.push({});};
/* del */
const del = (index) => {  actionData.splice(index, 1);};

/* ------优雅der校验所有form------ */

const validate = (refs) => {   
    const promises = refs.map((form, index) => form.validate());   
    return Promise.all(promises);
};

/* submit */
async function submit = () => {
    try {
        rule = await validate(this.$refs.actionForm);   
    } catch (e) {     
        rule = e;   
    };   
    if (!rule) {     
        return false;   
    } else {     
        /* todo*/   
   }
};

5、总结

  • 1、for 循环体 或者map里是不支持await。

  • 2、避免层层嵌套的回调校验。

  • 3、代码简洁清晰

彩蛋

如果验证失败自动滚定位到校验失败的位置:

const restpotion = () => {  
    let anchor = document.querySelectorAll('.el-form-item__error')[0]; 
        anchor.scrollIntoView({
            block: 'end',                
            behavior: 'smooth',  
    });
};