给出此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
上设置事件处理程序?
答案 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
}
}