Trigger an event on route change in Vue | VueJS
This article is about how we can trigger an event when we change routes in vueJS. We will use watch method and beforeRouteUpdate guard to detect the changes in routes.
This article is about how to trigger an event on route change in Vuejs with vue-router.
There are more than one way by which we can detect the route change in VueJS and trigger an event that can change a data value or run a function.
We can use the watch method and the beforeRouteUpdate() guard to detect route changes in $routes and trigger an event.
What is watch and beforeRouteUpdate() navigation guard?
The watch property in vue listens to data in a component and triggers whenever the value of the particular data changes. Here we will be watching the $route object changes.
The beforeRouteUpdate() navigation guard, lets you take an action before the route changes or you can prevent the route change with the next() function. For example, you can wait to fetch data before you go to the next route.
Trigger Event on route change
To trigger the event we will try both the methods in this example.
To react to route change in the same component, we can just use the watch property on $route object.
export default { data() { return { show: true }; }, watch: { $route(to, from) { this.show = false } } };
Here we have changed the vale of show from true to false when we change the route.
Another way is to use the beforeRouteUpdate() navigation guard.
export default { data() { return { show: true }; }, beforeRouteUpdate(to, from, next) { this.show = false next() } };
Here we have changed the value first and then call next() to change to a different route.
NOTE: The
beforeRouteUpdateguard only works on the view in which the method is declared and not on child components
Related Topics:
Related Posts
Easy Way to use localStorage with Vue
Short article on how to use local storage with Vue and learn saving and storing data in local storage with the setItem() and getItem() methods.
Force update Vue to Reload/Rerender component
Short tutorial on how to correctly force update Vue.js component to reload or rerender. The component is reinitialized without having to do a browser refresh.
Set and get cookies in a browser in Vue App
Find out how to set and get cookies in a browser for your webpage in Vue using vue-cookies package.
Save vuex state after page refresh in Vue App
Short tutorial on how to save (or persist) data in a vue application using Vuex and vuex-persist npm package.
