
1.首先定位到需要编辑的列,替换el-table-column
<template>
<el-table
:data="tableData"
style="width: 100%"
ref=tableRef
border>
<el-table-column type="index" label="序号" width="50" align="center" fixed="left"/>
<el-table-column prop="id" label="主键" width="100" v-if="false"/>
<el-table-column prop="date" label="时间" width="180"/>
<el-table-column prop="name" label="名称" 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>
</template>
2.el-table 标签下面增加 cell-click 事件,当某个单元格被点击时会触发该事件
<template>
<el-table
:data="tableData"
style="width: 100%"
ref=tableRef
@cell-click="showUnitInput"
border>
<el-table-column type="index" label="序号" width="50" align="center" fixed="left"/>
<el-table-column prop="id" label="主键" width="100" v-if="false"/>
<el-table-column prop="date" label="时间" width="180"/>
<el-table-column prop="name" label="名称" 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>
</template>
<script lang="ts" setup name="tableindex">
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)
}
</script>
4.增加一个样式,使可编辑的单元格鼠标悬停时显示虚线边框
<style lang="scss" scoped>
.hover-border {
border: none; /* 默认无边框 */
}
.hover-border:hover {
border: 1px dotted #165DFF; /* 鼠标悬停时显示虚线边框 */
padding: 2px;
}
</style>