vue3 中使用 HotKeys.js 教程(按键响应、快捷键开发)

2,013 阅读1分钟

在hooks 封装 HotKeys.js

hooks/useHotKey.ts

import hotkeys, { KeyHandler } from 'hotkeys-js'
import { onMounted, onUnmounted } from 'vue'

const useHotKey = (keys: string, callback: KeyHandler) => {
  onMounted(() => {
    hotkeys(keys, callback)
  })
  onUnmounted(() => {
    hotkeys.unbind(keys, callback)
  })
}

export default useHotKey

在vue3 项目使用

创建初始化文件 initHotKeys.ts

import useHotKey from '@/hooks/useHotKey'
export default function initHotKeys() {
  console.log(1111)
  useHotKey('esc', () => {
    alert('esc')
  })
}

使用

<template>
  <div class="">useHotKey 测试</div>
</template>

<script lang="ts">
import { defineComponent } from 'vue'
import initHotKeys from './initHotKeys'
export default defineComponent({
  setup() {
    initHotKeys()
  }
})
</script>

<style></style>