vue实现快捷键
监听键盘事件
在Vue中实现快捷键功能,可以通过监听键盘事件来完成。使用@keydown或@keyup指令绑定事件到组件或全局窗口。
<template>
<div @keydown.ctrl.enter="handleShortcut">
<!-- 内容 -->
</div>
</template>
<script>
export default {
methods: {
handleShortcut(event) {
if (event.ctrlKey && event.key === 'Enter') {
// 执行快捷键逻辑
}
}
}
}
</script>
全局快捷键监听
若需监听全局快捷键,可在mounted钩子中添加事件监听,并在beforeDestroy钩子中移除。

export default {
mounted() {
window.addEventListener('keydown', this.handleGlobalShortcut);
},
beforeDestroy() {
window.removeEventListener('keydown', this.handleGlobalShortcut);
},
methods: {
handleGlobalShortcut(event) {
if (event.ctrlKey && event.key === 'S') {
event.preventDefault();
// 保存操作
}
}
}
}
使用修饰键
Vue提供内置按键修饰符,如.enter、.tab、.esc等。结合修饰键(.ctrl、.shift、.alt)可组合成复杂快捷键。

<template>
<input @keyup.alt.67="copyText" />
</template>
<script>
export default {
methods: {
copyText() {
// Alt + C 触发复制
}
}
}
</script>
第三方库
对于复杂快捷键需求,可使用第三方库如vue-shortkey或hotkeys-js。以hotkeys-js为例:
import hotkeys from 'hotkeys-js';
export default {
mounted() {
hotkeys('ctrl+shift+k', () => {
// 自定义操作
});
},
beforeDestroy() {
hotkeys.unbind('ctrl+shift+k');
}
}
动态快捷键绑定
通过动态绑定按键码或修饰键,实现可配置的快捷键功能。
export default {
data() {
return {
shortcutKey: 'ctrl+space'
};
},
watch: {
shortcutKey(newVal) {
hotkeys.unbind(this.shortcutKey);
hotkeys(newVal, this.handleDynamicShortcut);
}
},
methods: {
handleDynamicShortcut() {
// 动态快捷键逻辑
}
}
}






