vue3table中的知识点
编辑table的格子进行操作
当鼠标浮动上面
cell-mouse-enter 当单元格 hover 进入时会触发该事件
<template>
<el-table :data="tableData" stripe style="width: 100%" @cell-mouse-enter="handleRowHover">
<el-table-column label="Name" prop="name">
<template #default="scope">
<el-input v-if="scope.row === editingRow" v-model="scope.row.name" @blur="handleSave(scope.$index)" />
<span v-else @click.stop="scope.row === editingRow ? null : handleEdit(scope.$index)">{{ scope.row.name }}</span>
</template>
</el-table-column>
<!-- 示例其他列 -->
<el-table-column label="Age" prop="age">
<template #default="scope">
<el-input v-if="scope.row === editingRow" v-model.number="scope.row.age" @blur="handleSave(scope.$index)" />
<span v-else @click.stop="scope.row === editingRow ? null : handleEdit(scope.$index)">{{ scope.row.age }}</span>
</template>
</el-table-column>
<!-- 根据需要添加更多列 -->
</el-table>
</template>
const editingRow = ref(null);
// 控制编辑行
const handleRowHover = (row, rowIndex) => {
editingRow.value = row;
};
// 开始编辑
const handleEdit = (index) => {
editingRow.value = tableData[index];
};
// 保存编辑
const handleSave = async (index) => {
// 这里可以添加保存逻辑,比如发送请求到服务器
// 简化示例,直接关闭编辑状态
editingRow.value = null;
};
- 编辑行状态: 引入了
editingRow
变量来记录当前正在编辑的行。当鼠标悬浮在某一行上时,通过handleRowHover
方法设置该行作为editingRow
。 - 事件调整: 使用
@cell-mouse-enter
事件替代之前的@cell-mouseenter
和@cell-mouseleave
,因为@row-hover
可以更直接地控制行级别的悬浮状态,但请注意,Element UI官方文档中没有直接的@row-hover
事件,这里是为了说明逻辑,实际上你可能需要自定义行的悬浮逻辑,比如使用第三方库或自定义指令来模拟这一行为。 - 编辑逻辑: 在每个单元格的模板中,判断当前行是否等于
editingRow
来决定显示输入框还是文本。点击文本时,只有在当前行不是编辑行时才触发编辑操作,避免在已编辑行上点击时重复进入编辑状态。
由于Element UI没有直接提供@cell-mouse-enter
事件,您可能需要自定义一个指令或使用第三方库来监听行的鼠标悬浮事件。上述示例侧重于逻辑说明,实际实现时,请根据您的具体情况调整事件监听方式。