Shyno
Don't be shy,no problem!

需求:在某一网页,通过上下左右键控制一些操作

 

实现:

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++
            }
        }
    }

 

posted on 2019-09-21 10:28  Shyno  阅读(18417)  评论(0编辑  收藏  举报