index.ts 478 B

123456789101112131415161718
  1. import { Directive, onUnmounted, DirectiveBinding } from 'vue'
  2. export const keyboard: Directive = {
  3. mounted (el, binding: DirectiveBinding) {
  4. const handleKeyPress = (event) => {
  5. if (event.key === 'Enter') {
  6. binding.value() // 执行绑定的方法
  7. }
  8. }
  9. el.addEventListener('keypress', handleKeyPress)
  10. // 在组件卸载时移除事件监听器
  11. onUnmounted(() => {
  12. el.removeEventListener('keypress', handleKeyPress)
  13. })
  14. }
  15. }