开发项目的时候遇到一个要求是当点击el-table的单元格时要对应将其变为可输入的输入框,研究了文档和网上的博客后,实现了这个效果
首先是表格的html部分,通过插槽scope进行表格的自定义,方便后续的元素格式转换
<el-table :data="Table.printData.data" stripe :border="true">
<el-table-column label="商品编号">
<template #default="scope">
<template v-if="scope.cellIndex == Table.cellIndex.value && scope.$index == Table.tableIndex.value">
<el-input v-model="scope.row.goodsid" @blur="Table.saveCell(scope,scope.$index)" v-focus />
</template>
<template v-else>
<div class="box" @click="Table.editCell(scope, scope.$index)">{{ scope.row.goodsid }}
</div>
</template>
</template>
</el-table-column>
<el-table-column label="打印数量">
<template #default="scope">
<template v-if="scope.cellIndex == Table.cellIndex.value && scope.$index == Table.tableIndex.value">
<el-input v-model="scope.row.PrintCount" @blur="Table.saveCell" v-focus />
</template>
<template v-else>
<div class="box" @click="Table.editCell(scope, scope.$index)">{{ scope.row.PrintCount }}</div>
</template>
</template>
</el-table-column>
</el-table>
然后是function部分,通过传入的scope和scope.$index来确定单元格位置以及所处的表格行数,并定义两个行和格变量进行条件判断,当行和格的值等于单元格的行和高的值时就把那个单元格的元素改为input,并通过自定义指令v-focus进行焦点的自动获取,当焦点失去时,将变量的值还原,同时绑定的单元格的值也会被随之改变
printTable是数组内容,对应table的字段添加就好了,这里不赘述
let Table = {
printData:reactive({data:[]}),
cellIndex: ref(-1),
tableIndex: ref(-1),
editCell: function (row, ind) {
Table.cellIndex.value = row.cellIndex;
Table.tableIndex.value = ind;
},
saveCell: function (type, id, index) {
Table.cellIndex.value = -1;
Table.tableIndex.value = -1;
}
}
在main.ts文件注册自定义指令
app.directive('focus', {
mounted(el) {
el.querySelector('input').focus();
}
});
到此就完成功能的开发了