我有输入和列表的问题,我想从下面的输入到列表元素,并将类'active'添加到当前的li元素
<div class="control">
<label class="label">Input Test</label>
<input type="text" class="input" @keydown="keyHandler">
<ul>
<li v-for="suggestion in suggestions" v-bind:class="{active}">{{suggestion.message}}</li>
</ul>
</div>
methods : {
keyHandler(e){
if(e.keyCode === 38){
e.preventDefault();
console.log('arrow up')
this.currentKey = e.key
}
else if(e.keyCode === 40){
e.preventDefault();
console.log('arrow down')
this.currentKey = e.key
}
}
}
这里是小提琴:https://jsfiddle.net/o8fwf0gh/13/
我很感激帮助
答案 0 :(得分:4)
希望这有帮助。
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
答案 1 :(得分:1)
您可以做的是更新数据属性,让我们说selected
,您应该在列表中的哪个位置。默认情况下,我们将其设置为0,以便选择第一个元素:
data: {
selected: 0,
// other data stuff
}
当按向上或向下箭头时,您显然必须更新此选项。
methods : {
keyHandler(e){
if(e.keyCode === 38){
e.preventDefault();
this.selected--;
}
else if(e.keyCode === 40){
e.preventDefault();
this.selected++;
}
}
}
然后您可以设置列表:
<li v-for="(suggestion, index) in suggestions" :class="index === selected ? 'active' : ''">{{suggestion.message}}</li>
您在class属性中看到的内容被称为简写语法。它基本上是一个if语句,返回&#39; active&#39;如果索引等于当前选择的列表编号。如您所见,索引作为v-for中的第二个属性传递。
如果我理解你正在努力实现的目标,这应该可以解决问题。 :P