stxkeybind
v0.0.4
Published
更新了readme
Readme
Keybind Vue 插件
一个支持 Vue2 和 Vue3 的全局快捷键插件,支持组合键、作用域、解绑等功能。
安装
npm install @your-scope/keybind引入插件
Vue 3
import { createApp } from 'vue';
import App from './App.vue';
import KeybindPlugin from '@your-scope/keybind/packages/src';
const app = createApp(App);
app.use(KeybindPlugin);
app.mount('#app');Vue 2
import Vue from 'vue';
import KeybindPlugin from '@your-scope/keybind/packages/src';
Vue.use(KeybindPlugin);快捷键绑定用法
绑定快捷键
// 在组件中
this.$key('ctrl+s', (e) => {
// 你的逻辑
e.preventDefault();
alert('保存快捷键触发');
});解绑快捷键
this.$key.unbind('ctrl+s');设置作用域
this.$key.setScope('modal');
// 只在 modal 作用域下生效
this.$key('esc', 'modal', () => { /* ... */ });判断按键是否按下
if (this.$key.isPressed('ctrl')) {
// ...
}作用域(Scope)用法说明
作用域(Scope)可以让你在不同的业务场景下动态切换快捷键响应区域,避免全局冲突。例如:在弹窗、表单、主界面等不同区域分别绑定不同的快捷键。
1. 绑定作用域快捷键
// 只在 "modal" 作用域下生效
this.$key('esc', 'modal', () => {
// 关闭弹窗逻辑
});2. 切换当前作用域
// 切换到 "modal" 作用域
this.$key.setScope('modal');
// 切换回全局作用域
this.$key.setScope('all');3. 结合使用示例
// 进入弹窗时
this.$key.setScope('modal');
// 离开弹窗时
this.$key.setScope('all');4. 获取当前作用域
const currentScope = this.$key.getScope();
console.log(currentScope); // 输出当前作用域名5. 解绑指定作用域下的快捷键
// 只解绑 modal 作用域下的 esc 快捷键
this.$key.unbind('esc', 'modal');提示:只有当前作用域与绑定时一致,快捷键才会生效。未指定作用域时,默认是 "all" 全局作用域。
直接使用 Keybinder API(适用于 Vue2/Vue3/普通 JS 工程)
如果你不想通过全局 this.$key,也可以直接引入 Keybinder 对象进行操作:
import { Keybinder } from "stxkeybind";
Keybinder.setScope("complex");
Keybinder("ctrl+s", "complex", (e) => {
// 你的逻辑
});这样可以在 Vue2、Vue3 组件外,普通 JS 文件或 setup 语法糖中灵活调用。
API
$key(keyCombo, [scope], handler)绑定快捷键$key.unbind(keyCombo, [scope])解绑$key.setScope(scope)设置当前作用域$key.getScope()获取当前作用域$key.isPressed(key)判断某键是否按下$key.getPressedKeyCodes()获取当前按下的所有 keyCode
License
MIT
