vue实现键盘选择
监听键盘事件
在Vue中实现键盘选择功能,可以通过监听键盘事件来触发相应的操作。使用@keydown或@keyup指令绑定事件处理函数,例如:
<template>
<div @keydown.up="handleUp" @keydown.down="handleDown">
<!-- 内容 -->
</div>
</template>
处理方向键逻辑
在事件处理函数中,根据按键类型更新选中项的状态。通常需要维护一个currentIndex变量来跟踪当前选中的位置:
methods: {
handleUp() {
this.currentIndex = Math.max(0, this.currentIndex - 1)
},
handleDown() {
this.currentIndex = Math.min(this.items.length - 1, this.currentIndex + 1)
}
}
焦点管理
确保可交互元素能够接收键盘事件,需要正确管理DOM焦点。对于自定义组件,可能需要使用tabindex属性:
<div
v-for="(item, index) in items"
:key="index"
:tabindex="0"
@focus="currentIndex = index"
>
{{ item }}
</div>
样式反馈
通过动态类绑定提供视觉反馈,让用户明确当前选中项:
<div
v-for="(item, index) in items"
:class="{ 'active': currentIndex === index }"
>
{{ item }}
</div>
完整示例代码
<template>
<div
@keydown.up.prevent="moveUp"
@keydown.down.prevent="moveDown"
@keydown.enter="selectItem"
tabindex="0"
>
<div
v-for="(item, index) in items"
:key="index"
:class="{ 'active': index === currentIndex }"
@click="currentIndex = index"
>
{{ item.text }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
currentIndex: 0,
items: [
{ text: '选项1' },
{ text: '选项2' },
{ text: '选项3' }
]
}
},
methods: {
moveUp() {
this.currentIndex = Math.max(0, this.currentIndex - 1)
},
moveDown() {
this.currentIndex = Math.min(this.items.length - 1, this.currentIndex + 1)
},
selectItem() {
console.log('选中:', this.items[this.currentIndex])
}
},
mounted() {
this.$el.focus()
}
}
</script>
<style>
.active {
background-color: #eee;
}
</style>
注意事项
确保组件在挂载后能够获取焦点,通常在mounted钩子中调用focus()方法。对于更复杂的场景,可以考虑使用Vue的自定义指令或第三方库如vue-hotkey来简化实现。







