在vue项目中监听键盘事件的方法


1在main.js文件中写入以下代码: Vue.prototype.$keyBoard = function (vm, methodName, code) {   document.onkeydown = function () {     let key = window.event.keyCode;     if (key == code) {       vm[methodName](code); // 触发methodName事件     }   }; }   2在需要监听键盘事件的组件里的mounted 生命周期内写入:   mounted () {     this.$keyBoard(this, 'onClickEnter', 13) // 13就是回车键的keycode,这样点击回车就能触发onClickEnter这个事件了   },   3在组件中定义被键盘事件触发的方法:   methods: {     onClickEnter () {       alert('哈哈')     }, }
vue