首页 > 解决方案 > 在事件处理程序中引用 `this` vue 组件

问题描述

鉴于这个附加了全局事件监听器的 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

标签: javascriptvue.jsvue-component

解决方案


实际上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);
    }
},

推荐阅读