在事件处理程序中引用`this` vue组件

时间:2020-05-30 14:59:02

标签: javascript vue.js vue-component

给出此Vue组件,该组件附加了全局事件侦听器:

var app = new Vue({
    data: {
        foo: 0;
    },
    methods: {
        handle: function(e) {
            this.foo = 1; // this refers to handler, not app
        }
    },
    mounted: function() {
        window.addEventListener("keypress", this.handle);
    }
});

从事件处理程序中引用this以更新组件状态的正确方法是什么?另外,是否有更好的方法在整个window上设置事件处理程序?

2 个答案:

答案 0 :(得分:3)

实际上this已绑定到vue实例,您的代码运行正常。

var app = new Vue({
    el: "#app",
    data: {
        foo: 0
    },
    methods: {
        handle: function(e) {
            this.foo++; 
            console.log(this.foo);
        }
    },
    mounted: function() {
        window.addEventListener("keypress", this.handle);
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
{{ foo }}
</div>

常见的错误是,例如,如果您有一个带有回调的函数,并且尝试在回调中使用this,它将是undefined

    handle: function(e) {
        this.foo++; 
        setTimeout(function(){
           console.log(this.foo); //undefined
        })
        console.log(this.foo);
    }

您可以使用箭头功能

    handle: function(e) {
        this.foo++; 
        setTimeout(() =>{
           console.log(this.foo);
        })
        console.log(this.foo);
    }
},

或者如果需要向后兼容,则可以使用.bind()

    handle: function(e) {
        this.foo++; 
        setTimeout(function(){
           console.log(this.foo);
        }.bind(this))
        console.log(this.foo);
    }
},

答案 1 :(得分:0)

您的数据属性应该是一个函数,而不是对象。

data(){
 return {
  foo: 1
 }
}
相关问题