Yuv*_*dam 6 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);
}
});
Run Code Online (Sandbox Code Playgroud)
this从事件处理程序中引用以更新组件状态的正确方法是什么?或者,有没有更好的方法来设置整个事件处理程序window?
实际上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);
}
});Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
{{ foo }}
</div>Run Code Online (Sandbox Code Playgroud)
常见的错误是,例如,如果您有一个带有回调的函数,并且您尝试this在回调中使用,它将是undefined
handle: function(e) {
this.foo++;
setTimeout(function(){
console.log(this.foo); //undefined
})
console.log(this.foo);
}
Run Code Online (Sandbox Code Playgroud)
您可以使用箭头函数
handle: function(e) {
this.foo++;
setTimeout(() =>{
console.log(this.foo);
})
console.log(this.foo);
}
},
Run Code Online (Sandbox Code Playgroud)
或者如果它需要向后兼容,你可以使用 .bind()
handle: function(e) {
this.foo++;
setTimeout(function(){
console.log(this.foo);
}.bind(this))
console.log(this.foo);
}
},
Run Code Online (Sandbox Code Playgroud)