Focus Input by Keydown
HTML
<div id="app">
<div>
<i-component v-for="item in items" :key="item.id"
autofocus
ref="inputs"
@focus.native="changeInput(item)"
@blur.native="current = null"
@keydown.left.native.prevent="focusPrevItem"
@keydown.right.native.prevent="focusNextItem"
>
</i-component>
{{current}}
</div>
</div>
<template id="input">
<input type="text">
</template>
JavaScript
var INPUT = {
template: '#input'
}
new Vue({
el: '#app',
data: function () {
return {
items: [
{ id: 1, text: '11111' },
{ id: 2, text: '22222' },
{ id: 3, text: '33333' }
],
current: null
}
},
components: {
'i-component': INPUT
},
computed: {
currentIndex: function () {
return this.items.findIndex(i => {
return i.id === this.current.id
})
}
},
watch: {
current: function (val, oldVal) {
if (val === null) {
return
}
console.log(val, oldVal)
console.log('this.currentIndex : ', val)
this.$refs.inputs[this.currentIndex].$el.focus()
}
},
methods: {
changeInput: function (item) {
this.current = item
},
focusPrevItem: function () {
var prevIndex = this.currentIndex - 1
if (prevIndex < 0) {
prevIndex = 0
}
console.log('focusPrev')
this.current = this.items[prevIndex]
},
focusNextItem: function () {
var nextIndex = this.currentIndex + 1
if (nextIndex === this.items.length) {
nextIndex = this.items.length - 1
}
console.log('focusNext : ', nextIndex)
this.current = this.items[nextIndex]
}
}
})