1、《template》代码如下(示例):
<template>
<div>
<hr/>
<div v-for="(item, index) in this.list" :key="index">
<el-input
v-model="item.name"
placeholder="请输入内容"
style="width: 200px; margin-right: 5px;">
</el-input>
<el-select v-model="item.value" placeholder="请选择" style="margin-right: 5px;">
<el-option
v-for="item in options"
:key="item.value"
:label="item.label"
:value="item.value">
</el-option>
</el-select>
<el-button
type="primary"
icon="el-icon-circle-plus-outline"
circle
@click="change(index, 'add')">
</el-button>
<el-button
v-if="index !== 0 || list.length !== 1"
type="danger"
icon="el-icon-remove-outline"
circle
@click="change(index, 'delet')">
</el-button>
</div>
</div>
</template>
2、《js》代码如下(示例):
<script>
export default {
data() {
return {
list: [{name: '', value: ''}],
options: [{value: '选择1', label: 'hello'}],
}
},
methods: {
change(index, type) {
if(type === 'add') {
// 1.点击添加时候从0开始,取list数组长度减一
const last = this.list.length - 1;
// 2.list 数组每增加一条数据取出对应值
const name = this.list[last].name;
const value = this.list[last].value;
this.list.push({
name,
value,
})
} else {
// 3. 点击减的时候删除list数组下标为index的一条数据
this.list.splice(index, 1);
}
}
},
}
</script>