1、需求是在使用表格时(用el-table举例),表格内有输入框,需要用上下左右键来切换到上下行输入框。
表格代码,
<el-table
:data='tableData.data'
:loading='loading'
:height='tableHeight'
style='width: 100%;'
class='list-table default-scrollbar'
size='mini'
border>
<el-table-column align='center' class-name='cellDefault' v-for='(item,index) in colList' :key='index' min-width='150' :prop='item.prop' :label='item.label'>
<template slot-scope="scope" v-if="scope.row.calctype===''||scope.row.isExitChildren!==true">
<el-input style='width: 120px' size='small' v-model="scope.row[item.prop]"
oninput="value=value.replace(/^\.+|[^\d.]/g,'')"
:ref="`inputs_${scope.$index}`"
@keydown.native="handleKeydown(this,$event,scope.$index)"> </el-input>
</template>
<template slot-scope="scope" v-else>
<span > {{scope.row[item.prop]}}</span>
</template>
</el-table-column>
</el-table>
2,在开发中给el-input加了@keydown.arrowup.native事件,然后console,怎么也监听不到,用了一下方法,键盘每个按键,在按下的的时候都会有不同的值,通过值来判断按下的哪个键进行监听。当某一行没有输入框,或者第一行、最后一行应该进行判断,返回最上层或者最下层还是不在对键盘进行监听。
例如:
handleKeydown(vm,event,currentIndex){
//这里会根据event.keycode判断,按下的是那个键
if(event.keyCode === 38){
//上箭头
this.handleArrowUp(currentIndex);
}else if(event.keyCode === 40){
//下箭头
this.handleArrowDown(currentIndex);
}
},
handleArrowUp(currentIndex) {
const prevIndex = currentIndex - 1;
if (prevIndex >= 0) {
this.focusInput(prevIndex,'up');
} else {
// 如果已经是第一行,可以选择不操作或滚动到最后一行
this.focusInput(this.tableData.data.length - 1);
}
},
handleArrowDown(currentIndex) {
const nextIndex = currentIndex + 1;
if (nextIndex < this.tableData.data.length) {
this.focusInput(nextIndex,'down');
} else {
// 如果已经是最后一行,可以选择不操作或滚动到第一行
this.focusInput(0);
}
},
focusInput(index,direction) {
// 通过Vue的$refs获取输入框DOM并设置焦点
const inputs = this.$refs[`inputs_${index}`];
if (inputs && inputs[0]) {
const input = inputs[0];
input.focus();
this.currentFocusedInput = input;
} else {
if(direction === 'down'){
this.handleArrowDown(index)
}else if(direction === 'up'){
this.handleArrowUp(index)
}
}
},