Working from this我有以下代码:
export default {
data(){
return {
width: 0,
height: 0,
}
},
methods: {
resizedWindow: _.throttle(this.reset, 200),
reset(){
this.width = window.innerWidth;
this.height = window.innerHeight;
}
},
mounted(){
this.reset();
window.addEventListener('resize', this.resizedWindow);
}
}
但这给了我以下错误:
未捕获的TypeError:无法读取未定义的属性“重置”
通常,这与this
有关,而我(通常)知道如何解决该问题。您可以执行以下操作:
// Replace previous resizeWindow with...
resizedWindow(){
let vm = this;
_.throttle(vm.reset, 200);
},
但这永远不会触发reset
方法。我知道对我this
的理解一定是愚蠢或空白–我该如何进行这项工作?
答案 0 :(得分:1)
在您的情况下,似乎this
是指window
对象。您可以将resizedWindow
方法定义移到created
钩子as seen here上,以访问this
作为Vue实例..
export default {
data(){
return {
width: 0,
height: 0,
}
},
methods: {
reset(){
this.width = window.innerWidth;
this.height = window.innerHeight;
}
},
created() {
this.resizedWindow = _.throttle(this.reset, 200)
},
mounted(){
this.reset();
window.addEventListener('resize', this.resizedWindow);
}
}
或者,您可以使用IIFE
..
export default {
data(){
return {
width: 0,
height: 0,
}
},
methods: {
resizedWindow() { (_.throttle(this.reset, 200))() },
reset(){
this.width = window.innerWidth;
this.height = window.innerHeight;
}
},
mounted(){
this.reset();
window.addEventListener('resize', this.resizedWindow);
}
}