当前位置:   article > 正文

Vue+ElementUI做一个批量新增的动态表单(增加/删除表单)_vue表单的批量操作

vue表单的批量操作

先看效果图:
在这里插入图片描述
表单代码展示:

<template>
  <div>
    <el-form v-for="ruleForm in ruleForm" :key="ruleForm" :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
      <el-row>
        <el-col :span="12">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="ruleForm.name"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="性别" prop="sex">
            <el-input v-model="ruleForm.sex"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="备注" prop="memo">
        <el-input v-model="ruleForm.memo"></el-input>
      </el-form-item>
      <el-divider></el-divider>
    </el-form>
    <el-form>
      <el-form-item label-width="100px">
        <el-button type="primary" @click="submitFormAdd()">保存并关闭</el-button>
        <el-button @click="resetForm()">重置</el-button>
        <el-button @click="add">+</el-button>
        <el-button @click="reduce" :disabled="flag">-</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

在data初始化表单, flag是控制如果只有一个表单的时候删除表单按钮为禁用状态

data() {
    return {
      // 表单
      ruleForm: [
        {
          name: '',
          sex: '',
          memo: ''
        }
      ],
      flag: true
    }
  }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

methods中的方法:

methods{
	// 表单添加一行
    add() {
      var arr = { name: '', sex: '', memo: '' }
      this.ruleForm.push(arr)
      this.flags()
    },
    // 表单减少一行
    reduce() {
      this.ruleForm.length = this.ruleForm.length - 1
      this.flags()
    },
    // 判断数组长度
    flags() {
      if (this.ruleForm.length < 2) {
        this.flag = true
      } else {
      	//先赋值为true再赋为false, 不然会没反应
        this.flag = true
        this.flag = false
      }
    },
    // 重置方法
    resetForm() {
      this.ruleForm = [{}]
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27

每次点击+按钮, 就会添加一个表单进去, 点击-按钮就会将数组的长度-1, 当数组长度小于2的时候, 就将-按钮禁用, 至此, 一个动态表单就完成实现了

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/91297
推荐阅读
相关标签
  

闽ICP备14008679号