vue form表单循环校验

发布时间:2024年01月24日

<template>
  <div class="box">
    <el-form :model="item" :rules="rules" :ref="`formRef_${index}`" v-for="(item,index) in ruleForm" :key="index">
      <div class="content">
        <Title :title="`机构${index+1}`" />
        <el-form-item label="机构名称" prop="name">
          <el-input v-model="item.name" class="w-340" maxlength="50"></el-input>
        </el-form-item>
        <el-form-item label="机构属性" class="checkbox-group" prop="type">
          <el-checkbox-group v-model="item.type">
            <el-checkbox label="管理中心" name="1"></el-checkbox>
            <el-checkbox label="推广中心" name="2"></el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </div>
      <div class="btn">
        <el-button @click="del(index)" v-if="ruleForm.length >1">删除</el-button>
        <el-button @click="add">添加</el-button>
      </div>
    </el-form>

    <el-button style="margin-top:100px" type="primary" @click="submitForm">提交</el-button>
  </div>
</template>

<script>
export default {
  data () {
    return {
      rules: {
        name: [
          { required: true, message: '请输入机构名称', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择机构属性', trigger: 'change' }
        ]
      },
      ruleForm: [
        {
          name: '',
          type: []
        }
      ]
    }
  },
  methods: {
    del (index) {
      this.ruleForm.splice(index, 1)
    },
    add () {
      this.ruleForm.push(
        {
          name: '',
          type: []
        }
      )
    },
    // 提交
    submitForm () {
     const arr = []
      this.ruleForm.forEach(async (item, index) => {
        try {
          await this.$refs[`formRef_${index}`][0].validate()
          arr.push(true)
        } catch (error) {
          arr.push(false)
        }
        const flag = arr.every(item => item)
        console.log(flag)
      })
    }
  }
}
</script>

<style lang="less" scoped>
.box {
  margin: 300px;
}
</style>

文章来源:https://blog.csdn.net/qq_41588991/article/details/135828635
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。