通过基础的Table表格来实现单元格内容的可编辑
1.首先定位到需要编辑的列,替换el-table-column
html
<el-table-column label="Editable Column" width="300">
<template #default="{ row, column, $index }">
<el-input
size="small"
v-if="
tableRowEditId === row.id &&
tableColumnEditIndex === column.id
"
v-model="row.taskId"
@blur="blurUnitInput(row, column)"
@keyup.enter="blurUnitInput(row, column)"
/>
<span v-else class="hover-border">{{ row.taskId }}</span>
</template>
</el-table-column>
2.el-table 标签下面增加 cell-click 事件,当某个单元格被点击时会触发该事件
html
<el-table :data="tableData" border style="width: 100%" @cell-click="showUnitInput">
<el-table-column prop="date" label="Date" width="180" />
<el-table-column prop="name" label="Name" width="180" />
<el-table-column label="Editable Column" width="300">
<template #default="{ row, column, $index }">
<el-input
size="small"
v-if="
tableRowEditId === row.id &&
tableColumnEditIndex === column.id
"
v-model="row.taskId"
@blur="blurUnitInput(row, column)"
@keyup.enter="blurUnitInput(row, column)"
/>
<span v-else class="hover-border">{{ row.taskId }}</span>
</template>
</el-table-column>
</el-table>
3. 增加标识变量、事件方法,可以在 blurUnitInput 方法里面实现修改的接口
javascript
const tableRowEditId = ref()
const tableColumnEditIndex = ref()
const showUnitInput = (row: any, column: any) => {
// console.log('row', row)
// console.log('column', column)
//赋值给定义的变量
tableRowEditId.value = row.id //确定点击的单元格在哪行 如果数据中有ID可以用ID判断,没有可以使用其他值判断,只要能确定是哪一行即可
tableColumnEditIndex.value = column.id //确定点击的单元格在哪列
}
const blurUnitInput = (row: { [x: string]: boolean }, column: any) => {
tableRowEditId.value = null
tableColumnEditIndex.value = null
//在此处调接口传数据
console.log(row)
console.log(column)
}
4.增加一个样式,使可编辑的单元格鼠标悬停时显示虚线边框
css
.hover-border {
border: none; /* 默认无边框 */
}
.hover-border:hover {
border: 1px dotted #165DFF; /* 鼠标悬停时显示虚线边框 */
padding: 2px;
}