vue实现箭头控制选项
使用 Vue 实现箭头控制选项
监听键盘事件
在 Vue 组件中监听键盘事件,可以通过 @keydown 或 @keyup 指令实现。通常选择 keydown 事件以便及时响应。
<template>
<div @keydown.down="moveDown" @keydown.up="moveUp" tabindex="0">
<!-- 选项列表 -->
<div v-for="(item, index) in items" :key="index" :class="{ active: index === activeIndex }">
{{ item }}
</div>
</div>
</template>
注意:tabindex="0" 使 div 可聚焦,从而接收键盘事件。
定义数据和方法
在 Vue 的 data 中定义选项列表和当前选中索引,并在 methods 中实现移动逻辑。
<script>
export default {
data() {
return {
items: ['选项1', '选项2', '选项3', '选项4'],
activeIndex: 0
}
},
methods: {
moveUp() {
this.activeIndex = Math.max(0, this.activeIndex - 1)
},
moveDown() {
this.activeIndex = Math.min(this.items.length - 1, this.activeIndex + 1)
}
}
}
</script>
添加样式反馈
通过 :class 绑定动态样式,高亮当前选中项。
<style>
.active {
background-color: #f0f0f0;
font-weight: bold;
}
</style>
支持回车确认
扩展键盘事件处理,加入回车键确认逻辑。
methods: {
handleKeyDown(e) {
switch (e.key) {
case 'ArrowUp':
this.moveUp()
break
case 'ArrowDown':
this.moveDown()
break
case 'Enter':
this.selectItem(this.items[this.activeIndex])
break
}
},
selectItem(item) {
console.log('选中:', item)
// 执行选中后的操作
}
}
自动聚焦组件
在 mounted 钩子中自动聚焦组件,确保无需点击即可接收键盘事件。
mounted() {
this.$el.focus()
}
完整示例代码
<template>
<div
@keydown="handleKeyDown"
tabindex="0"
class="select-container"
>
<div
v-for="(item, index) in items"
:key="index"
:class="{ active: index === activeIndex }"
class="select-item"
>
{{ item }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: ['选项1', '选项2', '选项3', '选项4'],
activeIndex: 0
}
},
methods: {
moveUp() {
this.activeIndex = Math.max(0, this.activeIndex - 1)
},
moveDown() {
this.activeIndex = Math.min(this.items.length - 1, this.activeIndex + 1)
},
handleKeyDown(e) {
switch (e.key) {
case 'ArrowUp': this.moveUp(); break
case 'ArrowDown': this.moveDown(); break
case 'Enter': this.selectItem(this.items[this.activeIndex]); break
}
},
selectItem(item) {
alert(`已选择: ${item}`)
}
},
mounted() {
this.$el.focus()
}
}
</script>
<style>
.select-container {
outline: none;
}
.select-item {
padding: 8px 12px;
cursor: pointer;
}
.active {
background-color: #e0f7fa;
font-weight: bold;
}
</style>
注意事项
- 确保组件或其父元素可获得焦点,否则键盘事件无法触发
- 处理边界情况(如列表为空时)
- 考虑添加防抖处理(如果选项切换涉及异步操作)
- 移动端可能需要额外处理触摸事件
此实现适用于大多数需要键盘导航的场景,如自定义下拉菜单、导航菜单或列表选择器。根据实际需求可扩展更多功能,如循环导航、多级菜单等。






