这里主要使用了el-table三个自带的方法/属性:
clickCell:单元格的点击事件,用于根据当前点击的行列信息决定变成输入框的cell。
row-class-name与cell-class-name用于获取每个单元格的行列信息以便定位cell。
// 把每行的索引放进row中
tableRowClassName({ row, rowIndex }) {
row.index = rowIndex;
},
// 把每列的索引放进column中
tableCellClassName({ column, columnIndex }) {
column.index = columnIndex;
},
这样,在点击的时候就可以获取到相关信息了:
clickCell(row, column){
// 获取行列Index并存在一个数组中
this.activeCellIndex = [row.index, column.index];
// 使其获取焦点
this.$nextTick(() => {
this.$refs['tab'+row.index+column.index].focus()
})
},
(表格处部分代码展示,根据activeCellIndex判断是否展示el-input框)
{{scope.row.value1}}
{{scope.row.value2}}
即可实现效果:
可能1:需在定时器或nextTick中获取ref并focus()。
可能2:有时提高ref获取焦点时可以打印出ref对应DOM,但是focus却不生效。
后来笔者通过document.querySelectorAll方法发现获取到的该类名的Dom不止一个。经过排查是el-table的一列设置了fixed(固定)所导致的。设置它会自动生成一列并不显示,造成focus失效的假象。
解决方法:获取第一个符合条件的Dom并获取其焦点。(是这个思路,解决方法不唯一)
以下是笔者的解决方案:
1.先为el-input定义类名,方便获取:
2.获取真正的input并获取其焦点(方法不一,这里使用的jQuery)
clickCell(row, column){
this.activeCellIndex = [row.index, column.index];
this.$nextTick(() => {
let aimDom = (document.querySelectorAll('.'+'tab'+row.index+column.index));
// 此处打印aimDom发现有两个dom,组成一个数组。
// this.$refs['tab'+row.index+column.index].focus(); //失效的原方法
// 获取第一个符合条件的目标Dom,并获取焦点(笔者这里用的jQuery实现)
// 因为el-input中的input标签是包裹在其中的,所以获取其children并focus()。
$('.'+'tab'+row.index+column.index).children()[0].focus();
})
},
效果实现!
希望本文会对你有所帮助~ ^_^