Javascript 在Vue中使用lodash油门时通过此选项
我有以下代码:Javascript 在Vue中使用lodash油门时通过此选项,javascript,vue.js,this,lodash,Javascript,Vue.js,This,Lodash,我有以下代码: export default { data(){ return { width: 0, height: 0, } }, methods: { resizedWindow: _.throttle(this.reset, 200), reset(){ this.width = window.innerWidth; this.height = window.innerHeight; }
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:无法读取未定义的属性“reset”
通常这与这个有关,我(通常)知道如何解决这个问题。你可以这样做:
// Replace previous resizeWindow with...
resizedWindow(){
let vm = this;
_.throttle(vm.reset, 200);
},
但这不会触发reset
方法。我知道这一定是我对这件事的理解有点愚蠢或差距-我如何才能使这件事起作用?在你的情况下这件事似乎是指窗口
对象。您可以将resizedWindow
方法定义移动到创建的钩子中,以作为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);
}
}
或者,您可以使用iLife
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);
}
}
“this”是未定义的,因为\u0.throttle(this.reset,200)
甚至在“exports”赋值之前就调用对象定义,所以“this”的引用是窗口(或者在您的情况下是未定义的,因为您启用了严格模式)。