keypress.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. // #ifdef H5
  2. export default {
  3. name: 'Keypress',
  4. props: {
  5. disable: {
  6. type: Boolean,
  7. default: false
  8. }
  9. },
  10. mounted () {
  11. const keyNames = {
  12. esc: ['Esc', 'Escape'],
  13. tab: 'Tab',
  14. enter: 'Enter',
  15. space: [' ', 'Spacebar'],
  16. up: ['Up', 'ArrowUp'],
  17. left: ['Left', 'ArrowLeft'],
  18. right: ['Right', 'ArrowRight'],
  19. down: ['Down', 'ArrowDown'],
  20. delete: ['Backspace', 'Delete', 'Del']
  21. }
  22. const listener = ($event) => {
  23. if (this.disable) {
  24. return
  25. }
  26. const keyName = Object.keys(keyNames).find(key => {
  27. const keyName = $event.key
  28. const value = keyNames[key]
  29. return value === keyName || (Array.isArray(value) && value.includes(keyName))
  30. })
  31. if (keyName) {
  32. // 避免和其他按键事件冲突
  33. setTimeout(() => {
  34. this.$emit(keyName, {})
  35. }, 0)
  36. }
  37. }
  38. document.addEventListener('keyup', listener)
  39. this.$once('hook:beforeDestroy', () => {
  40. document.removeEventListener('keyup', listener)
  41. })
  42. },
  43. render: () => {}
  44. }
  45. // #endif