在el-table中点击单元格时使用el-input或其他表单组件编辑单条数据。会出现聚焦不上的问题,需要手动点击才能够聚焦。究其原因是因为点击单元格时页面已自动聚焦到单元格,此时无法自动聚焦到对应的表单,需要手动设置。
javascript
<template>
<el-table
:data="tableData"
@cell-click="cellclickHandle"
>
<el-table-column prop="text" label="编辑" align="right">
<template #default="{ row }">
<el-input
v-focus
style="height: 20px"
v-model="row.text"
@blur="cellBlur(1, row)"
v-if="row?.isEdit ?? false"
/>
<span v-else>{{ row.text }}</span>
</template>
</el-table-column>
</el-table>
</template>
<script setup>
import { reactive } from "vue"
....
//自定义指令
const vFocus = {
mounted: el => {
//清除el-table的cell聚焦
document.activeElement.blur()
const targetInput = el.getElementsByTagName("input")[0]
targetInput.focus()
}
}
//表格点击
let cacheRow = reactive({})
const cellclickHandle = (row, column) => {
const { property } = column
if (!["text"].includes(property)) return
cacheRow = JSON.parse(JSON.stringify(row))
if (property === "text") {
row.isEdit = true
}
}
const cellBlur = async (input, row) => {
row.isEdit = false
if (cacheRow.text == row.text) return
await ...
ElMessage.success("编辑成功")
}
</script>
<style lang="scss" scoped>
</style>