当前位置: 代码迷 >> 综合 >> vue+iview 实现v-for循环出来的多表单验证
  详细解决方案

vue+iview 实现v-for循环出来的多表单验证

热度:17   发布时间:2023-11-21 06:21:47.0

vue+iview 实现v-for循环出来的多表单验证
单个表单验证就不多赘述了,很简单,方法如下

 <Form ref="formValidate" :model="formList" :rules="rulesValidate">  ......</Form>export default {
    data(){
    return{
    formList:{
    username: '',password: ''},rulesValidate: {
    username: [{
    required: true, message: '账号不能为空', trigger: 'blur'}],password: [{
    required: true, message: '密码不能为空', trigger: 'blur'}]}}},methods: {
    handleSubmit(){
    this.$refs['formValidate'].validate((valid) => {
    if (valid) {
    //验证通过}})}}}

那么用v-for循环实现的多表单的验证方法如何实现呢,具体实现方法如下

<div  v-for="(pItem,pIndex) in formList" :key="'pi' + pIndex" style="margin:5px 0;"><Form :ref="'formValidate' + pIndex" :model="pItem" :rules="rulesValidate">......</Form>
</div>export default {
    data(){
    return{
    formList:[{
    name:'',age:''},{
    name:'',age:''},{
    name:'',age:''}],rulesValidate: {
    name: [{
    required: true, message: '姓名不能为空', trigger: 'blur'}],age: [{
    required: true, message: '年龄不能为空', trigger: 'blur'}]}}},methods: {
    handleSubmit(){
    this.formList.forEach((item, index) => {
    let form = 'formValidate' + index;this.$refs[form][0].validate((valid) => {
    if (valid) {
    arr.push(true);} else {
    arr.push(false);}});});let flag = arr.every((item) => {
    return item === true;});if(flag){
    //全部为true,验证通过//验证通过}else{
    this.$Message.error('信息填写有误');return false;}}}}