gpt4 book ai didi

javascript - 在 Vue 中使用 lodash throttle 时传递这个

转载 作者:行者123 更新时间:2023-11-30 20:06:31 25 4
gpt4 key购买 nike

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);
}
}

但这给了我以下错误:

Uncaught TypeError: Cannot read property 'reset' of undefined

通常这与 this 有关,我(通常)知道如何修复它。你做这样的事情:

// Replace previous resizeWindow with...
resizedWindow(){
let vm = this;
_.throttle(vm.reset, 200);
},

但这不会触发 reset 方法。我知道这一定是我对this 的理解上的一些愚蠢或差距——我怎样才能让它工作?

最佳答案

在您的例子中,this 似乎指的是 window 对象。您可以将 resizedWindow 方法定义移动到 created Hook as seen here作为 Vue 实例访问 this ..

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);
}
}

关于javascript - 在 Vue 中使用 lodash throttle 时传递这个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52888735/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com