I am trying to throttle a method in my VueJS application. I tried the following at first:
export default {
data () {
return {
foo: 'bar'
}
},
methods: {
doSomething () {
console.log('olas')
}
},
created () {
_.throttle(this.doSomething,200)
}
}
But the doSomething
method was just not fired: https://jsfiddle.net/z4peade0/
Then, I tried this:
export default {
data () {
return {
foo: 'bar'
}
},
methods: {
doSomething: _.throttle( () => {
console.log('olas')
},200)
},
created () {
this.doSomething()
}
}
And the functiong gets triggered: https://jsfiddle.net/z4peade0/1/
Problem is, I can't access the foo
property inside the throttled method:
export default {
data () {
return {
foo: 'bar'
}
},
methods: {
doSomething: _.throttle( () => {
console.log(this.foo) // undefined
},200)
},
created () {
this.doSomething()
}
}
I tried to do something like:
const self = {
...
methods: {
doSomething: _.throttle( () => {
console.log(self.foo)
},200)
},
...
}
export default self
without success
How could I use lodash throttled method on a VueJS method, and using this
context?
throttle() method in lodash is used to create a throttled function that can only call the func parameter maximally once per every wait milliseconds.
Yes you can inject some Vue into a project built with regular JavaScript or jQuery. It's not all or nothing. You can pass data between JavaScript and Vue because it you're dealing with JavaScript objects.
Lodash is a JavaScript library that is packed with a bunch of goodies 🍬. Unlike Halloween goodies that means you have to do laps around your neighborhood to burn those extra calories.
You're using an arrow function, which binds the wrong context (this
). You should use a plain function
:
doSomething: _.throttle( function () {
console.log('olas', this.foo);
},200)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With