希望這有助於感謝。
var app = new Vue({
el: '#form',
data: {
currentKey: null,
suggestions: [{
message: 'Foo'
}, {
message: 'Bar'
}, {
message: 'Foobar'
}, {
message: 'pikachu'
}, {
message: 'raichu'
}],
active: false
},
methods: {
keyHandler(e) {
if (e.keyCode === 38) {
e.preventDefault();
console.log('arrow up')
this.setActiveClass(this.currentKey, e.key)
this.currentKey = e.key
} else if (e.keyCode === 40) {
e.preventDefault();
this.setActiveClass(this.currentKey, e.key)
console.log('arrow down')
this.currentKey = e.key
}
},
setActiveClass(previousKey, currentKey) {
if (previousKey) {
var tempIndex = this.suggestions.findIndex(x => x.class == "active");
this.$set(this.suggestions[tempIndex], 'class', 'inactive')
if (currentKey === 'ArrowDown') {
if (tempIndex === this.suggestions.length - 1)
this.$set(this.suggestions[0], 'class', 'active')
else
this.$set(this.suggestions[tempIndex + 1], 'class', 'active')
} else {
if (tempIndex === 0)
this.$set(this.suggestions[this.suggestions.length - 1], 'class', 'active')
else
this.$set(this.suggestions[tempIndex - 1], 'class', 'active')
}
} else {
if(currentKey === 'ArrowUp')
this.$set(this.suggestions[this.suggestions.length - 1], 'class', 'active')
else
this.$set(this.suggestions[0], 'class', 'active')
}
}
}
}
})
,並在HTML中,你可以做到以下幾點:
<li v-for="suggestion in suggestions" v-bind:class='suggestion.class'>{{suggestion.message}}
工作實例here
這是完美的!感謝 – matithedeveloper
你能告訴我如何改變你的提琴當數據建議: 「富」, 「酒吧」, 「Foobar的」, 「皮卡丘」, 「的Raichu」],這裏是提琴:HTTPS: //jsfiddle.net/o8fwf0gh/19/我得到「無法創建屬性」類的字符串「錯誤 – matithedeveloper
我使用的方法只適用於具有對象數組的情況。現在您已將其更改爲字符串數組。所以解決方案不適合您的新需求。 – Pradeepb