vue+element-ui 实现table单元格点击编辑,并且按上下键单元格之间切换
作者:互联网
1.接到需求是点击键盘上下键,控制输入框移动方便输入数据
2.相关实现代码
<el-table-column label="Pageviews" width="110" align="center">
<template slot-scope="scope">
<el-input-number
style="width:90%"
:controls="false"
:min="0"
@input.native="inputChange($event,scope.$index)"
@change="(currentval,oldval)=>onChange(currentval,oldval,scope)"
v-model="scope.row.pageviews"
size="mini"
/>
</template>
</el-table-column>
_handleInputChange(value) {
const newVal = value === '' ? undefined : Number(value);
if (!isNaN(newVal) || value === '') {
return newVal
}
return 0
},
inputChange(e,i){
const value = this._handleInputChange(e.target.value)
this.$set(this.list[i],'pageviews',value);
},
onChange(newval,oldval,scope){
document.onkeydown = (e) => {
var curel = document.activeElement.parentElement.parentElement.parentElement; //当前元素
var curcellIndex = curel.parentElement.cellIndex; // 当前元素行单元格索引
var curRowIndex = curel.parentElement.parentElement.sectionRowIndex; //当前元素行的索引;
var curtbody = curel.parentElement.parentElement.parentElement.children; //当前tbody内容的整个表单
if (e.keyCode == 38) {
this.$set(this.list[scope.$index],'pageviews',oldval);
//按上键
if (curRowIndex - 1 < 0) {
curtbody[curtbody.length - 1].children[
curcellIndex
].getElementsByTagName('input')[0].focus();
} else {
curtbody[curRowIndex - 1].children[
curcellIndex
].getElementsByTagName('input')[0].focus();
}
}
else if (e.keyCode == 40 || e.keyCode == 13) {
//向下按钮按键
e.preventDefault();
this.list[scope.$index].pageviews = oldval;
if (curRowIndex + 1 == curtbody.length) {
curtbody[0].children[curcellIndex].getElementsByTagName('input')[0].focus();
} else {
const td = curtbody[curRowIndex + 1].children[
curcellIndex
].getElementsByTagName('input')[0];
td.focus()
}
}
}
},
3.其他
- 因为上下键切换,组件值会发生改变,所以相应在onChange函数强行把值绑定回来
- 不知道为啥鼠标点击手动输入时不会触发v-model,所以用了inputChange绑定值,组件el-input-number的number检测就没啥用了,直接换成el-input组件document.onkeydown还可以少写些单词了,不过懒了,这就不改了
- 实现思路①一开始打算试试动态改变tabindex;②后面看见有现成的大佬博主内容(相当于用鼠标在点击-聚焦)就改造改造了,非常感谢!
原文:https://www.cnblogs.com/Tohold/p/9559092.html
标签:vue,parentElement,单元格,value,element,curRowIndex,input,curtbody,children 来源: https://blog.csdn.net/qq_42220283/article/details/118067972