Vue中怎么实现回车键切换焦点
可以看到,如果每一个输入框都是这种类型的嵌套结构,上面的方法是无法直接解决的。因为 nextElementSibling API 只能找到下一个兄弟元素,而在这里 input 明显找不到下一个兄弟元素。
思路是,通过回溯的手段朝外层寻找,直到找到一个类名包含 el-form-item 和 el-form-item--small 的祖级元素,然后再从这个祖级元素的下一个兄弟元素中寻找类名包含 el-input__inner 的 input 元素。
所以要再写两个函数,分别是寻找组件元素的 findFormItem 和寻找 input 元素的 findInput 。
findFormItem:
functionfindFormItem(el){
constparent=el.parentElement;
if(!parent)returndocument.body;
if(
parent.className.includes("el-form-item")&&
parent.className.includes("el-form-item--small")
){
returnparent;
}
returnfindFormItem(parent);
}findInput:
functionfindInput(container){
letnextEl=container.nextElementSibling;
if(!nextEl)return;
letinput=nextEl.querySelector("input");
while(input.id==="el-select"){
nextEl=nextEl.nextElementSibling;
if(!nextEl)return;
input=nextEl.querySelector("input");
}
if(input.className.includes("el-input__inner"))returninput;
}有了这两个函数以后,实现回车切换焦点就非常简单了。只需要执行两行代码。
constcontainer=findFormItem(document.activeElement); findInput(container)&&findInput(container).focus();
完整的代码大概是这样的。
在 methods 中声明三个方法。
methods:{
addEnterListener(){
if(window.__completeEnterBind__)return;
window.addEventListener("keydown",this.enterCallback);
window.__completeEnterBind__=true;
},
removeEnterListener(){
window.removeEventListener("keydown",this.enterCallback);
window.__completeEnterBind__=false;
},
enterCallback(e){
functionfindFormItem(el){
constparent=el.parentElement;
if(!parent)returndocument.body;
if(
parent.className.includes("el-form-item")&&
parent.className.includes("el-form-item--small")
){
returnparent;
}
returnfindFormItem(parent);
}
functionfindInput(container){
letnextEl=container.nextElementSibling;
if(!nextEl)return;
letinput=nextEl.querySelector("input");
while(input.id==="el-select"){
nextEl=nextEl.nextElementSibling;
if(!nextEl)return;
input=nextEl.querySelector("input");
}
if(input.className.includes("el-input__inner"))returninput;
}
if(e.keyCode===13){
constcontainer=findFormItem(document.activeElement);
findInput(container)&&findInput(container).focus();
}
}
}然后在 mounted 中添加回车监听和在 destroy 中移除回车键听。
mounted(){
this.addEnterListener();
},
destroy(){
this.removeEnterListener();
},需要注意的是,项目是多标签页的形式,表单组件可能会被渲染多次,所以通过在 window 对象上添加一个 __completeEnterBind__ 字段来确保回车换行事件正确绑定。
感谢你能够认真阅读完这篇文章,希望小编分享的“Vue中怎么实现回车键切换焦点”这篇文章对大家有帮助,同时也希望大家多多支持恰卡编程网,关注恰卡编程网行业资讯频道,更多相关知识等着你来学习!
海报
169
目录
