v-for中动态校验el-form表单项怎么用(el-form,v-for,开发技术)

时间:2024-05-05 12:20:37 作者 : 石家庄SEO 分类 : 开发技术
  • TAG :

问题描述

在项目开发中,我们经常会遇到表单保存的功能,在表单保存前,常常需要做表单必填项的校验,校验通过以后才去发请求保存表单数据。

但是,这个表单如果是动态的,即:可以新增相同的表单。比如这个表单有输入框和下拉框需要校验,点击添加表格按钮,再新增一个相同的表单,同样新的这个表单对应的输入框和下拉框也需要校验。

我们先看一下效果图:

效果图

v-for中动态校验el-form表单项怎么用

代码思路

  • 表单的主数据是要写成对象形式 :model="ruleForm" 不过既然是要动态的,肯定是要循环呢,所以,可以写成这样:

ruleForm:{//动态循环项数组formItemArr:[{name:"",gender:"",},],},
  • 点击添加表格的时候,就可以直接push对应项就行啦,即,这样:

//添加一个表格addForm(){letitemObj={name:"",gender:"",};this.ruleForm.formItemArr.push(itemObj);},
  • 重点来喽,因为是循环的,所以prop也要变成动态的了,要拼接上index,就变成根据索引去找对应的校验项了,即为::prop="'formItemArr.' + index + '.name'" ,这样的话,就变成了:prop="formItemArr.0.name"prop="formItemArr.1.name"prop="formItemArr.2.name" ... 这样的话,就可以照顾到每一项中的每一个绑定的值了,校验就不会漏掉

  • 校验规则写成内联就可以触发校验函数this.$refs["ruleForm"].validate((val) => {})

<el-form-itemlabel="姓名":prop="'formItemArr.'+index+'.name'":rules="{required:true,message:'请填写',trigger:'blur',}">......

完整代码

演示的话,大家直接复制粘贴即可

<template><divclass="box"><el-button@click="addForm"size="mini"type="primary"plain>添加表格</el-button><el-button@click="saveForm"size="mini"type="primary"plain>保存表格</el-button><br/><br/><el-form:model="ruleForm"ref="ruleForm"label-width="100px"class="formform"><divclass="formformItemClass"v-for="(item,index)inruleForm.formItemArr":key="index"><el-form-itemlabel="姓名":prop="'formItemArr.'+index+'.name'":rules="{required:true,message:'请填写',trigger:'blur',}"><el-inputsize="mini"v-model.trim="item.name"placeholder="请填写"></el-input></el-form-item><el-form-itemlabel="性别":prop="'formItemArr.'+index+'.gender'":rules="{required:true,message:'请选择',trigger:'change',}"><el-selectclearablesize="mini"v-model="item.gender"placeholder="请选择"><el-optionlabel="男"value="男"></el-option><el-optionlabel="女"value="女"></el-option></el-select></el-form-item></div></el-form></div></template><script>exportdefault{data(){return{ruleForm:{//动态循环项数组formItemArr:[{name:"",gender:"",},],},};},methods:{//添加一个表格addForm(){letitemObj={name:"",gender:"",};this.ruleForm.formItemArr.push(itemObj);},//保存表格saveForm(){this.$refs["ruleForm"].validate((val)=>{if(val){console.log("符合要求,保存成功",this.ruleForm);}else{console.log("errorsubmit!!");returnfalse;}});},},};</script><stylelang="less"scoped>.box{width:100%;height:100%;box-sizing:border-box;padding:24px;.formform{width:360px;.formformItemClass{padding-top:24px;border:2pxdashed#ccc;margin-bottom:18px;}}}</style>
 </div> <div class="zixun-tj-product adv-bottom"></div> </div> </div> <div class="prve-next-news">
本文:v-for中动态校验el-form表单项怎么用的详细内容,希望对您有所帮助,信息来源于网络。
上一篇:el-table嵌套el-popover处理卡顿如何解决下一篇:

14 人围观 / 0 条评论 ↓快速评论↓

(必须)

(必须,保密)

阿狸1 阿狸2 阿狸3 阿狸4 阿狸5 阿狸6 阿狸7 阿狸8 阿狸9 阿狸10 阿狸11 阿狸12 阿狸13 阿狸14 阿狸15 阿狸16 阿狸17 阿狸18