elementUI Table单元格双击编辑,失焦保存
核心代码如下:
<!-- 表格 --> <template> <el-table :data="testDatas" @header-contextmenu="(column, event) => rightClick(null, column, event)" @row-contextmenu="rightClick" :row-class-name="tableRowClassName" > <template v-for="(item, index) in tableColumns"> <el-table-column v-if="item.prop && !item.hidden" :key="index" :min-width="item.minWidth ?? 160" :width="item.width" :label="item.label" :prop="item.prop" > <!-- 核心代码开始 --> <template v-slot:header> <p v-if="item?.editHeader" @dblclick="item.show = false"> {{ item.label }} <el-icon><EditPen /></el-icon> </p> <span v-else>{{ item.label }}</span> </template> <template #default="{ row, $index }"> <template v-if="item.type === 'edit'"> <!-- row为元数据,$index为该列的'键' --> <p v-show="!row.show" @dblclick="() => dblclick(row, $index + 1)"> {{ row[item.prop] }} <el-icon @click="row.show = true"><EditPen /></el-icon> </p> <!-- 失去焦点时更改"show"属性,显示文本 --> <el-input ref="saveTagInput" type="input" v-show="row.show" v-model="row[item.prop]" @blur="row.show = false" /> </template> <!-- 核心代码结束 --> </template> </el-table-column> </template> </el-table> </template> <script lang="ts" setup> import { ref, nextTick } from 'vue' const saveTagInput = ref() /** * 双击显示input框并自动获取焦点 * 失焦保存数据的话,可以在'@blur'方法里将修改后的数据update到数据库中 */ const dblclick = (row, key) => { row.show = true nextTick(() => { saveTagInput.value[key]?.focus() }) } </script>