最近写了一个需求,点击单元格可以进行编辑,编辑完成之后,点击保存,将编辑之后的数据传给后端。
效果图:
实现代码
一.HTML
1.在el-table标签注册 @cell-click="editName" :key="randomKey"
2.在需要编辑的单元格el-table-column 加入template—input输入框
<el-table v-loading="loading" :data="deliveryList" @selection-
change="handleSelectionChange" @cell-click="editName" :key="randomKey">
<el-table-column label="金额" align="center" prop="price" >
<template slot-scope="scope">
<el-input
v-if="scope.row[scope.column.property + 'isShow']"
:ref="scope.column.property"
v-model="scope.row.price"
@blur="alterData(scope.row, scope.column)"
oninput="if(isNaN(value)) { value = null } if(value.indexOf('.')>0)
{value=value.slice(0,value.indexOf('.')+3)}"
></el-input>
<span v-else>{{ scope.row.price }}</span>
</template>
</el-table-column>
<el-table-column label="服务类型" align="center" prop="serviceType" />
</el-table>
注:οninput="if(isNaN(value)) { value = null } if(value.indexOf('.')>0) 校验小数点后面限制两位,我的应用场景里面有这个需求,所以这句可加可不加
二.JS
data:{
randomKey: Math.random(),
list1:[],
}
methods:{
editName(row, column) {
if(column.label=='金额'){
//这里是点击让el-input显示
row[column.property + 'isShow1'] = true
//这里是编辑完一个存一个,存到list1里面,且将重复编辑的去掉(去重)
for(let index in this.list1){
if(this.list1[index].id==row.id){
this.list1.splice(index,1)
}
}
this.list1.push(row)
// refreshTable是table数据改动时,刷新table的
this.refreshTable()
this.$nextTick(() => {
this.$refs[column.property] && this.$refs[column.property].focus()
})
}
},
//表格触发事件
alterData(row, column) {
row[column.property + 'isShow'] = false
//this.refreshTable(),每编辑一个单元格,就会更新一下表格,如果数据量较大的时候,会编辑完一个单元格,表格更新,页面就会返回到顶部,你需要找到刚编辑过的地方,继续编辑,页面体验差,所以我没加
},
//更新表格
refreshTable() {
this.randomKey = Math.random()
},
//保存按钮
submitForm(){
//做金额不能为空值的限制
for (let index in this.list1){
if(this.list1[index].price==''){
this.$modal.msgWarning("金额不能有空值");
return
}
}
expensedelivery(this.list1).then(response => {
this.msgSuccess("保存成功");
this.list1=[]
this.getList();//刷新查询列表接口,这个里面的代码就不写了
});
}
}
以上就能实现编辑表格的功能,如果有什么疑问或者错误,欢迎询问和指正