對(duì)于動(dòng)態(tài)增減表單項(xiàng)撑蒜,Element UI 官方文檔表單那一節(jié)已經(jīng)介紹得很清楚了,但是沒(méi)有新增按鈕和刪除并列情況,這里針對(duì)點(diǎn)擊按鈕增刪一排輸入框的問(wèn)題做一個(gè)總結(jié)座菠。
先上效果
微信圖片_20200927102654.png
<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="設(shè)備編號(hào):"
label-width="90px"
style="margin-right: 10px"
>
<el-input
v-model="item.value"
placeholder="請(qǐng)輸入設(shè)備起始編號(hào)"
></el-input>
</el-form-item>
<el-form-item label="至"></el-form-item>
<el-form-item>
<el-input
v-model="item.name"
placeholder="請(qǐng)輸入設(shè)備起始編號(hào)"
></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>
動(dòng)態(tài)添加
batchAdd(index, length) {
if (this.batchForm[index].value !== "") {
this.batchForm.push({ name: "", value: "", index: length + 1 });
this.batchFormNum = length + 1;
} else {
this.$message.error("標(biāo)簽編號(hào)不能為空");
}
}
動(dòng)態(tài)刪除
//動(dòng)態(tài)刪除批量綁定數(shù)據(jù)
batchDel(index) {
if (this.batchForm.length <= 1) {
this.batchForm[index].value = "";
this.batchForm[index].index = 0;
this.batchFormNum = 0;
} else {
//先刪除當(dāng)前下標(biāo)的數(shù)據(jù)
this.batchForm.splice(index, 1);
let num = [];
//循環(huán)找出所有下標(biāo),不找出最大值狸眼,不根據(jù)順序刪除會(huì)報(bào)錯(cuò)
this.batchForm.forEach((item) => {
num.push(item.index);
});
//查出數(shù)組中最大值,賦值給batchFormNum
this.batchFormNum = Math.max(...num);
}
}
表單數(shù)據(jù)
batchForm: [
{
name: "",
value: "",
index: 0,
}
]浴滴,
batchFormNum: 0
batchFormNum 最大值:用來(lái)判斷增加按鈕顯示在最后