1, the preface

This article has participated in the activity of “New person creation Ceremony”, and started the road of digging gold creation together. In Web development, the front end is used to collect, verify, submit data and other scenarios will use form form, form form is the most convenient is very convenient to the user (customer) input value to do specific verification, such as: illegal input, mandatory default, etc. The validate method, which validates the entire form, usually accepts a callback argument or returns a promise with no arguments and waits for validation results before doing anything else. Today we are going to talk about the elegant validation of multiple forms generated in V-for in vUE.

2, achieve the effect

1. The whole outer layer is composed of one form, and the inner layer is composed of multiple forms. 2. Click Add Card to add a card in Label3, that is, add a FROM. Click X for each card to delete a card, that is, delete a form.

3, the View layer

<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>
Copy the code

4. Data layer

4.1, the data

ActionData: [{id: 'no1', name: 'front-end show '}];Copy the code

4.2 the methods,

/* add */ const add = () => { actionData.push({}); }; /* del */ const del = (index) => { actionData.splice(index, 1); }; /* ------ */ const promises = (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*/ } };Copy the code

5, summary

  • 1. The body of a for loop or map does not support await.

  • 2. Avoid layer upon layer of nested callback verification.

  • 3. The code is concise and clear

eggs

If verification fails, roll to the location where verification fails:

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