Vue.js VueJS采用lodash节流方法
我正在尝试限制VueJS应用程序中的方法。首先,我尝试了以下方法:Vue.js VueJS采用lodash节流方法,vue.js,lodash,Vue.js,Lodash,我正在尝试限制VueJS应用程序中的方法。首先,我尝试了以下方法: export default { data () { return { foo: 'bar' } }, methods: { doSomething () { console.log('olas') } }, created () { _.throttle(thi
export default {
data () {
return {
foo: 'bar'
}
},
methods: {
doSomething () {
console.log('olas')
}
},
created () {
_.throttle(this.doSomething,200)
}
}
但是doSomething
方法没有被触发:
然后,我试了一下:
export default {
data () {
return {
foo: 'bar'
}
},
methods: {
doSomething: _.throttle( () => {
console.log('olas')
},200)
},
created () {
this.doSomething()
}
}
并且函数G被触发:
问题是,我无法访问限制方法中的foo
属性:
export default {
data () {
return {
foo: 'bar'
}
},
methods: {
doSomething: _.throttle( () => {
console.log(this.foo) // undefined
},200)
},
created () {
this.doSomething()
}
}
我试着做一些类似的事情:
const self = {
...
methods: {
doSomething: _.throttle( () => {
console.log(self.foo)
},200)
},
...
}
export default self
无功而返
如何在VueJS方法上使用lodash节流方法,并使用
此上下文?
您使用的是一个箭头函数,它绑定了错误的上下文(此
)。您应该使用普通的函数
:
doSomething: _.throttle( function () {
console.log('olas', this.foo);
},200)
很好,我一点都不知道,非常感谢