I have a Vue component that uses multiple sub-components on it. And on those sub-components I have a watcher that watches for data changes and processes those changes. I would like to implement debounce for this.
watch: {
data: {
handler: function () {
this.processData()
},
deep: true
}
},
methods: {
processData: debounce(function () {
console.log(this.id)
}, 250),
The problem is that debounce works so it executes only on the last sub-component.
I have found a solution for debounce function that accepts an additional id debounceWithId
However there problem is that if I specify this function as follows:
methods: {
processData: debounceWithId(function () {
console.log(this.id)
}, 250, this.id),
the last this.id is undefined.
What would be a correct way of using debounce in multiple components so the function fires separately on each component?
First let me add an example that replicates the issue you are describing.
Essentially what is going on here is that the debounced function is created when the component is compiled, and each instance of the component shares the same debounced function. The context of
this
will be different in each one, but it is the same function. I added aconsole.log
in the generated debounced function so that you can see that all three components are sharing the same function. That being the case, the function is doing what it is designed to do; it executes once after the elapsed period of time, which is why only the last component is updated.To get around that behavior you need a unique debounce function for each component. Here are two ways you can do that.
Method One
You can initialize your processData method with what amounts to a placeholder.
Then, in the created lifecycle event, change the processData method to the debounced method.
This will give each component a unique debounced function and should take care of the issue where only the last component works properly.
Here is an example modified from the above example.
Method Two
Thanks to @RoyJ for suggesting this. You can define the
processData
method indata
. Typically you do not do this because you don't often want multiple copies of a function, and that's why themethods
section of a component definition exists, but in a case, like this where you need a unique function for each component, you can define the method in the data function because the data function is called for every instance of the component.Here is an example using that approach.