- 全局注册指令
Vue.directive('enterToNext',{
inserted:function(el){
let inputs = el.querySelectorAll('input');
for( var i = 0 ;i < inputs.length ; i++ ){
inputs[i].setAttribute("keyFocusIndex",i);
inputs[i].addEventListener('keyup', (ev) => {
if (ev.keyCode === 13) {
let targetTo = ev.srcElement.getAttribute('keyFocusTo');
if(targetTo){
this.$refs[targetTo].$el.focus();
}else{
var attrIndex = ev.srcElement.getAttribute('keyFocusIndex');
var ctlI = parseInt(attrIndex);
if(ctlI<inputs.length-1)
inputs[ctlI+1].focus();
}
}
});
}
},
- 使用(本示例使用的是elementui)
在el-form标签使用:v-enterToNext=“true”
<el-form ref="addForm" :rules="rules" :model="addForm" label-width="100px" id="addForm" v-enterToNext="true">