1,需求
vue项目中用到了一些键盘快捷键操作,虽然限制很多,但还是可以实现一些需求的,这里有两种方式可以做到,手写的和别人造的轮子哦~
2,手写代码
document.onkeydown = e => {
if ((e.ctrlKey || e.metaKey) && e.altKey && e.key === "b") {
box.setAttribute("class", "blue");
// 阻止默认事件
e.preventDefault();
};
if ((e.ctrlKey || e.metaKey) && e.altKey && e.key === "r") {
box.setAttribute("class", "red");
// 阻止默认事件
e.preventDefault();
};
}
ps:大写字母按键和小写字母按键是有区别的,比如Ctrl + Alt + r 和Ctrl + Alt + R,如果功能比较复杂,可以使用vue插件 vue-hotkey。
3,第三方插件
这里用的是大佬造的轮子 vue-hotkey。
安装
npm i --save v-hotkey
在main.js中引入
import Vue from 'vue'
import VueHotkey from 'v-hotkey'
Vue.use(VueHotkey)
组件内用法
<template>
<div>
<span v-hotkey.prevent="keymap" v-show="show">
按' ctrl + esc '切换我,按住'回车'隐藏
</span>
</div>
</template>
如果看了觉得有帮助的,我是@鹏多多i,欢迎 点赞 关注 评论;
END
公众号
往期文章
个人主页