对于动态增减表单项,Element UI 官方文档表单那一节已经介绍得很清楚了,但是没有新增按钮和删除并列情况,这里针对点击按钮增删一排输入框的问题做一个总结。
先上效果
<div class="binding-main">
<el-form ref="ruleForm" class="demo-ruleForm">
<div
class="binding-item"
v-for="(item, index) in batchForm"
:key="index"
>
<el-form-item
label="设备编号:"
label-width="90px"
style="margin-right: 10px"
>
<el-input
v-model="item.value"
placeholder="请输入设备起始编号"
></el-input>
</el-form-item>
<el-form-item label="至"></el-form-item>
<el-form-item>
<el-input
v-model="item.name"
placeholder="请输入设备起始编号"
></el-input>
</el-form-item>
<el-form-item label-width="10px" v-if="item.name != '' && item.value!==''">
<span
class="el-icon-close binding-button-close"
@click="batchDel(index)"
></span>
</el-form-item>
<el-form-item label-width="10px" v-if="batchForm[index].index == batchFormNum">
<span
class="el-icon-plus binding-button-plus"
@click="
batchAdd(index, batchForm[batchForm.length - 1].index)
"
></span>
</el-form-item>
</div>
</el-form>
</div>
动态添加
batchAdd(index, length) {
if (this.batchForm[index].value !== "") {
this.batchForm.push({ name: "", value: "", index: length + 1 });
this.batchFormNum = length + 1;
} else {
this.$message.error("标签编号不能为空");
}
}
动态删除
//动态删除批量绑定数据
batchDel(index) {
if (this.batchForm.length <= 1) {
this.batchForm[index].value = "";
this.batchForm[index].index = 0;
this.batchFormNum = 0;
} else {
//先删除当前下标的数据
this.batchForm.splice(index, 1);
let num = [];
//循环找出所有下标,不找出最大值,不根据顺序删除会报错
this.batchForm.forEach((item) => {
num.push(item.index);
});
//查出数组中最大值,赋值给batchFormNum
this.batchFormNum = Math.max(...num);
}
}
表单数据
batchForm: [
{
name: "",
value: "",
index: 0,
}
],
batchFormNum: 0
batchFormNum 最大值:用来判断增加按钮显示在最后