javascript - 在事件处理程序中引用 `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
?
解决方案
实际上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);
}
},
推荐阅读
- javascript - 如何减少 Phaser 中的 addEvent 延迟?
- java - SetCellValue 不适用于第一行 java
- internet-explorer - IE11中的页面加载为空
- c - I2C 读取功能在发送确认位后卡住
- amazon-dynamodb - 如何在 DynamoDB 中创建良好的主键
- openlayers-5 - 从 turf.js MultiPolygon 创建 OpenLayers 5 MultiPolygon 功能
- python - 高效的叠瓦算法
- vue-cli - (Nuxt)npm run dev 有错误,node_modules 错误
- oop - Robert Martin 所说的“只有函数从早期的编程时代存活下来,而不是例行公事”是什么意思?
- android - 我正在尝试在微调器中获取 Json 数据,但每次都失败