添加事件

mounted() {
    window.addEventListener('keydown', this.handleEvent)
},

 注销事件

beforeDestroy() {
    window.removeEventListener('keydown', this.handleEvent) // 在页面销毁的时候记得解除
},

监听方法 

async handleEvent(event) {
      switch (event.keyCode) {
        case 37:
          console.log('ctrl + ←')
          break
        case 38:
          console.log('ctrl + ↑')
          break
        case 39:
          console.log('ctrl + →')
          break
        case 40:
          console.log('ctrl + ↓')
          break
        case 67:
          console.log('ctrl + c')
          break
        case 83:
          console.log('ctrl + s')
          event.preventDefault()
          event.returnValue = false // 阻止直接保存网页
          // eslint-disable-next-line no-prototype-builtins
          if (event.ctrlKey && event.code === 'KeyS' && store.getters.forbidden.hasOwnProperty('ctrlS')) {
            // 在这里写保存需要执行的逻辑
          }
          if (event.ctrlKey && event.code === 'KeyS') return false
          break
        case 86:
          console.log('ctrl + v')
          break
        case 89:
          console.log('ctrl + y')
          if (event.ctrlKey && event.code === 'KeyY') {
            this.$router.go(+1)
          }
          break
        case 90:
          if (this.$route.path === '登录成功重定向的路由,比如控制台:/dashboard') return // 防止退出项目
          if (event.ctrlKey && event.code === 'KeyZ') {
            this.$router.go(-1)
          }
          break
      }
    }

Logo

前往低代码交流专区

更多推荐