实现一个动态表单,支持新增移动删除
代码如下:
<el-formref="form":model="grid"label-width="60px"style="width: 350px"><divv-for="(item, index) in list":key="item.type + index"class="area-config-form"><el-form-item label="类型" prop="type"><el-selectv-model="item.type"clearable:data="typeList"></bs-select></el-form-item><el-form-item label="标题" prop="title"><el-inputv-model="item.title"placeholder="请输入"></el-input></el-form-item><el-form-itemlabel="内容"prop="content"><el-inputv-model="item.content"type="textarea"placeholder="请输入"></el-input></el-form-item><div style="text-align: center"><el-buttonv-if="index !== 0"size="mini"icon="el-icon-top"@click="moveUp(index)"></el-button><el-buttonv-if="index !== list.length - 1"size="mini"icon="el-icon-bottom"@click="moveDown(index)"></el-button><el-buttonsize="mini"icon="el-icon-delete"@click="handleDelete(index)"></el-button></div></div></el-form><el-buttonsize="small"type="primary"style="width: 100%":icon="uiSetting.icon.addRow"@click="onAdd">新增</el-button>
js代码:
methods: {// 生成新数据generateNewData() {const data = {type: null,title: null,content: null,}return data},// 增加一行onAdd() {this.list.push(this.generateNewData())},// 删除当前行handleDelete(index) {this.$confirm2.warning('确定删除当前数据吗?').then(() => {this.list.splice(index, 1)}).catch(() => {})},// 上移moveUp(index) {if (index <= 0) returnconst temp = this.list[index]this.$set(this.list, index, this.list[index - 1])this.$set(this.list, index - 1, temp)},// 下移moveDown(index) {if (index >= this.list.length - 1) returnconst temp = this.list[index]this.$set(this.list, index, this.list[index + 1])this.$set(this.list, index + 1, temp)}}
效果图: