如图效果
1、对每一行数据添加是否编辑的标记(isEdit),通过forEach遍历数组,给每一项都添加isEdit,
如果直接 item.isEdit = false ,得到的数据是不具有响应式的
可以使用 this.$set(目标对象,属性名称,初始值) ,使目标对象具备响应式
2、不能直接修改数据里面的值,重新定义一个缓存数据,也是通过 this.$set
methods: {
async getRoles() {
const { data } = await getRolesService(this.page, this.pagesize)
this.roleList = data.rows
// 针对每一行数据添加一个编辑标记
this.roleList.forEach(item => {
// item.isEdit = false // 添加的动态属性 不具备响应式特点
// this.$set(目标对象,属性名称,初始值) 使目标对象具备响应式
this.$set(item, 'isEdit', false)
// 定义响应式的缓存数据
this.$set(item, 'editRow', {
name: item.name,
description: item.description,
state: item.state
})
})
}
}
3、在表格中使用 插槽、v-if判断,实现不同状态显示
4、编辑状态绑定的是之前定义的缓存数据
<el-table-column label="角色" prop="name" align="center" width="200px">
<template slot-scope="scope">
<el-input v-if="scope.row.isEdit" v-model="scope.row.editRow.name" />
<span v-else>{{ scope.row.name }}</span>
</template>
</el-table-column>
5、点击编辑的时候,改变行的编辑状态,把行的值赋值给缓存数据
editRow(row) {
console.log(row)
row.isEdit = true // 改变行的编辑状态
// 更新缓存数据
row.editRow.name = row.name
row.editRow.description = row.description
row.editRow.state = row.state
}
6、点击确定后,先判断输入框是否有值,有值后,更新显示的数据,退出编辑状态
直接 row.isEdit = false ,不符合Eslint规范,需要使用Object.assign()
Object.assign(target,sources) target:目标对象 sources:源对象
如果目标对象中的属性具有相同的键,则属性将被源对象中的属性覆盖,后面的源对象的属性将覆盖前面的目标对象的属性
async editOk(row) {
if (row.editRow.name && row.editRow.description) {
await editRoleService(row.id, row.editRow)
this.$message.success('修改成功')
// 更新显示数据 退出编辑状态
// Object.assign(target, source) target--->目标对象 source--->源对象
Object.assign(row, {
...row.editRow,
isEdit: false
}) // 规避eslint的误判
} else {
this.$message.warning('角色或描述不能为空')
}
}