Ant Design 表格动态添加行删除行实现
1、先看效果
点击添加产品按钮,产品详情表格里添加一行数据,通过选择产品下拉框,将产品的价格赋值给单价列
2、实现方式
(1)在代码中添加标签
标签中的dataSource是表格里的数据列表,columns是表格显示字段名,里添加模板标签,其中slot表示字段值相同的时候显示,columns里会定义scopedSlots字段名字,和templete里的slot匹配
<a-table :dataSource="list" :columns="columns" :pagination="false">
<template slot="productId" slot-scope="text, record">
<a-select v-model="record.productId" :placeholder="'请选择'" style="width: 100%"
@change="getProductPrice(record.productId)">
<a-select-option
v-for="(d, index) in productOptions"
:key="index"
:value="d.productId">
{{ d.productName }}
</a-select-option>
</a-select>
</template>
<template slot="productCount" slot-scope="text, record">
<a-input
style="margin: -5px 0"
v-model="record.productCount"
:placeholder="'请输入数量'"
/>
</template>
<template slot="price" slot-scope="text, record">
<a-input
style="margin: -5px 0"
v-model="record.price"
:placeholder="'请输入价格'"
disabled="disabled"
/>
</template>
<template slot="operation" slot-scope="text, record">
<a-popconfirm title="是否要删除此行?" @confirm="removeProduct(record.key,record.id)">
<a>删除</a>
</a-popconfirm>
</template>
</a-table>
(2)data中定义变量值
list: [],
columns: [
{
title: '产品',
dataIndex: 'productId',
ellipsis: true,
align: 'center',
scopedSlots: {customRender: 'productId'}
},
{
title: '产品数量',
dataIndex: 'productCount',
ellipsis: true,
align: 'center',
scopedSlots: {customRender: 'productCount'}
},
{
title: '单价',
dataIndex: 'price',
ellipsis: true,
align: 'center',
scopedSlots: {customRender: 'price'}
},
{
title: '操作',
dataIndex: 'operation',
width: '18%',
scopedSlots: {customRender: 'operation'},
align: 'center'
}
]
(3)增加添加表格方法及删除表格行方法
/**
* 表格中添加一行空数据
*/
removeProduct(key, id) {
if (id) {
delOrderPro(id).then(response => {
this.$message.success(
'删除成功',
3
)
const list = [...this.list];
this.list = list.filter(item => item.key !== key);
}).finally(() => {
this.submitLoading = false
})
} else {
const list = [...this.list];
this.list = list.filter(item => item.key !== key);
}
},
addTable() {
const {count, list} = this;
const newData = {
key: count,
id: undefined,
productId: undefined,
productCount: undefined,
price: undefined,
};
this.list = [...list, newData];
this.count = count + 1;
}
(4)点击修改按钮查询产品表格列表并在表格中进行展示
getInfo(orderId).then(response => {
this.form = response.data
this.list = response.data.products
if (this.list) {
for (let i = 0; i < this.list.length; i++) {
this.list[i].key = i; //删除行根据key值来删除,查询出来的列表需要给key赋值,不然无法删除
}
this.count = this.list.length; //给count赋值,再新添加就不会有重复值
}
this.open = true
this.formTitle = '修改'
})
(5)选择产品,将选择的产品的价格直接显示在表格的单价列
/**
* 根据下拉框选择的产品查询产品信息并将产品价格赋值给表格中的单价列
* @param id
*/
getProductPrice(id) {
getProductPrice(id).then(response => {
const item = this.list.find(item => item.productId === id);
item.price = response.data.productPrice;
})
}