Vue form enter event the next input gets focus
how to focus the next input after a dynamically generated set of input, triggers the enter event
<li class="border-none" v-for="(item,index) in prcHdAreaList" :key="item.pmcKeyVal">
<input
:ref="item.pmcKeyVal"
v-focus-next-on-enter=""item.pmcKeyVal""
name="item.phaRate" class="cus_input"
v-model.trim="item.phaRate" type="number"/>
</li>
Vue.directive("focusNextOnEnter", {
bind: function(el, {value}, vnode) {
el.addEventListener("keyup", (ev) => {
if (ev.keyCode === 13) {
let nextInput = vnode.context.$refs[value]
if (nextInput && typeof nextInput.focus === "function") {
nextInput.focus()
nextInput.select()
}
}
})
}
})
After several hours of trying, I implemented this requirement with custom instructions, using methods prov
ided by
vue
without using any native DOM operations and plug-ins.
< hr >
specific code (you can see the effect by copying and pasting directly, and comments have been made in important places):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="app">
<ul>
<li v-for="(item,index) in inputs">
<input type="text" v-model="item.val" v-focus="focusIndex === index" @keyup.enter="nextFocus(index)">
</li>
</ul>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script>
// `v-focus`
Vue.directive('focus', {
// DOM
inserted: function (el,obj) { //,
//console.log(obj);
if(obj.value) { //
//
el.focus()
}
},
// VNode VNode
componentUpdated: function(el,obj) { //
//console.log(obj); //
if(obj.value) {
el.focus()
}
}
})
new Vue({
el: "-sharpapp",
data() {
return {
focusIndex: 0, //index
inputs: [{
val: 1
},{
val: 2
},{
val: 3
},{
val: 4
}]
}
},
methods: {
nextFocus(index) {
return this.focusIndex = index + 1;
}
}
});
</script>
</body>
</html>
< hr >
I hope my answer will be helpful to you! Welcome to criticize and correct the inadequacies of ^ _ ^.
Let's go to the code directly-dynamic data, dynamic acquisition, dynamic focus-- ohye
var vm = new Vue({
el: ".wrap",
methods: {
fun() {
const DOM = event.target
const nextDOM = DOM.nextElementSibling
nextDOM.focus()
}
}
})
</script>
</div>
</body>
</html>
as shown in the code above, nextElementSibling gets the next sibling node, and then focus () gets focus