项目中遇到的一个客户需求,需要按Enter快捷键实现Tab按键的切换功能,且不能切换到指定界面外。
思路:绑定id、或者ref 都可以,根据逻辑再调用focus()进行聚焦即可。
解决方案如下:
<template>
<div style="display: flex;justify-content: flex-start;align-items: center;">
<!-- <el-input :id="'input_'+item" v-for="(item,index) in array" :key="index"></el-input> -->
<el-input :ref="'input_'+item" v-for="(item,index) in array" :key="index" @focus="changeFocus($event,item)"></el-input>
</div>
</template>
<script>
export default{
name:"keydownSwitch",
data(){
return{
icount:0,
array:[1,2,3],
tempRefName:'',
}
},
mounted() {
document.onkeydown = (e) => {
let e1 = e || event || window.event || arguments.callee.caller.arguments[0]
console.log(e1.keyCode)
if (e1 && e1.keyCode == 13) {
Object.defineProperty(e1, "keyCode", { value: 9 });
Object.defineProperty(e1, "code", { value: 'Tab' });
}
if (e1 && e1.keyCode == 9) {
e.preventDefault();//阻止默认事件
if(this.icount <3){
this.icount++;
}else{
this.icount = 1;
}
//document.getElementById("input_" + this.icount).focus(); // JavaScript写法
//ref 写法
this.tempRefName = "input_" + this.icount
this.$nextTick((x)=>{ //正确写法
this.$refs[`${this.tempRefName}`][0].focus();
//如果报错 focus() is not function
// 可以如下写: this.$refs[`${this.tempRefName}`][0].focus()
})
}
}
},
methods:{
changeFocus(event,item){
console.log('event',event,item)
this.icount = item;
}
}
}
</script>
以上仅作参考