i have a button
in my project when i click on it two queries
added to URL
onClickBtn(){
this.$router.push({queries: {name:'kevin' , age:21} })
}
and I have a watch
on $route
watch:{
$route:function(){
// call API
}
}
and when i click on that button
severall time
watch
calls my API
every time although nothing has changed
and this make a problem form me
because nothing has changed in route
But API
is called and the same data is
received .
what should I do to avoid calling API in watch
, when queries
don't changed ??
CodePudding user response:
The object you are pushing on the router is always different, that's why the $route watch is launched. You can compare the data you receive in the watch, so that when they are different then you invoke the API:
watch:{
'$route' (newRoute, lastRoute){
// Check if query is different
// call API
}
}
CodePudding user response:
On top of the answer that Cristian provided, you could also even double-check if your stuff has changed before even pushing a new object to your router.
Like this
checkIfUpdateNeeded && this.$router.push({queries: {name: 'kevin', age:21 } })
That way, you will have less moving parts and you won't have a trigger in the watcher for "nothing", especially if you're pushing a bigger object and want to make a deep-diff between 2 objects.