ElementUI table表格组件实现双击编辑单元格失去焦点还原,支持多单元格
在ElementUI的table组件中,要实现双击编辑后失去焦点还原单元格,可以通过监听dblclick
事件来启用输入框,并使用input
或blur
事件来处理编辑后的逻辑。以下是一个简单的实现示例:
<template>
<el-table :data="tableData" style="width: 100%">
<el-table-column v-for="item in columns" :key="item.prop" :prop="item.prop" :label="item.label">
<template slot-scope="scope">
<el-input
v-if="editable[scope.$index][item.prop]"
:ref="`editableCellInput_${scope.$index}_${item.prop}`"
v-model="scope.row[item.prop]"
@blur="handleInputBlur(scope.$index, item.prop)"
@input="handleInput(scope.$index, item.prop)"
size="small"
placeholder="请输入内容"
></el-input>
<span v-else @dblclick="handleDblClick(scope.$index, item.prop)">{{ scope.row[item.prop] }}</span>
</template>
</el-table-column>
</el-table>
</template>
<script>
export default {
data() {
return {
tableData: [
// ... 数据项
],
columns: [
// ... 列配置
],
editable: [] // 是否可编辑的状态数组,初始化为所有单元格不可编辑
};
},
methods: {
handleDblClick(index, prop) {
this.editable[index] = this.editable[index] || {};
this.editable[index][prop] = true;
this.$nextTick(() => {
const input = this.$refs[`editableCellInput_${index}_${prop}`][0];
input.focus();
});
},
handleInput(index, prop) {
// 可以在这里添加输入时的处理逻辑
},
handleInputBlur(index, prop) {
this.editable[index][prop] = false;
// 可以在这里添加失去焦点后的处理逻辑
}
}
};
</script>
在这个示例中,我们使用了一个二维数组editable
来记录每个单元格的编辑状态。在模板中,我们根据editable
数组的状态来决定是否显示el-input
组件。如果单元格不可编辑,则显示文本,并监听dblclick
事件来启动编辑状态。如果单元格可编辑,则显示el-input
组件,并在输入框blur
时还原状态。
评论已关闭