需求:在某一网页,通过上下左右键控制一些操作
实现:
1.基本代码:
因为没有绑定特定的元素.所以我们将事件绑定到document上.
//当前页面监视键盘输入 document.onkeydown = function(e) { console.log('键盘输入了') //事件对象兼容 let e1 = e || event || window.event || arguments.callee.caller.arguments[0] //键盘按键判断:左箭头-37;上箭头-38;右箭头-39;下箭头-40 //左 if (e1 && e1.keyCode == 37) { this.decrease() } else if (e1 && e1.keyCode == 38) { this.nowStudent-- } else if (e1 && e1.keyCode == 39) { this.increase() } else if (e1 && e1.keyCode == 40) { this.nowStudent++ } }
2.何时何处绑定:
其他绑定特定元素的函数,都是直接绑定在行内,也就是说创建时就绑定了
<input @keyup.enter="function">
而我们则需要把这个事件绑定过程放在created钩子中,理由很简单.在这个钩子里可以确定你想绑定的元素已经构建完成
created() { this.getHomework() //当前页面监视键盘输入 document.onkeydown = function(e) { console.log('键盘输入了') //事件对象兼容 let e1 = e || event || window.event || arguments.callee.caller.arguments[0] //键盘按键判断:左箭头-37;上箭头-38;右箭头-39;下箭头-40 //左 if (e1 && e1.keyCode == 37) { this.decrease() } else if (e1 && e1.keyCode == 38) { this.nowStudent-- } else if (e1 && e1.keyCode == 39) { this.increase() } else if (e1 && e1.keyCode == 40) { this.nowStudent++ } } },
3.this指向修正
完成以上两步,还不行.会报错.this.getHomework正常,console.log也会执行,但是onkeydown的this会出错.
Uncaught TypeError: this.decrease is not a function
原因是created钩子里的this是vue对象,但是,onkerdown这个函数本身又形成了一个"作用域",this指向了调用onkeydown的对象.而onkeydown里面的decrease()是methods里面的一个函数,所以this的指向出错
解决方案
用一个全局变量把this保存起来再用
created() { this.getHomework() var that = this //当前页面监视键盘输入 document.onkeydown = function(e) {//事件对象兼容 let e1 = e || event || window.event || arguments.callee.caller.arguments[0] //键盘按键判断:左箭头-37;上箭头-38;右箭头-39;下箭头-40 //左 if (e1 && e1.keyCode == 37) { that.decrease() } else if (e1 && e1.keyCode == 38) { that.nowStudent-- } else if (e1 && e1.keyCode == 39) { that.increase() } else if (e1 && e1.keyCode == 40) { that.nowStudent++ } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构