Trigger an event on route change in Vue | VueJS
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 beforeRouteUpdate guard only works on the view in which the method is declared and not on child components Related Topics: How to redirect to external url in vue? How to listen for props changes in VueJS?
Related Posts
How to Fix Error Code 0x80004005 in Windows (Complete Guide)
Learn how to fix error code 0x80004005 in Windows 11 and Windows 10. Follow step-by-step solutions for Windows update errors, ZIP extraction issues, network sharing problems, and VirtualBox errors with practical troubleshooting methods.
Fix ModuleNotFoundError: No module named google.cloud.bigquery (Step-by-Step Guide)
Learn how to fix ModuleNotFoundError no module named google.cloud.bigquery in Python. Follow step-by-step solutions for virtual environments, Jupyter, VS Code, and Docker with clear debugging tips.
How to Clear npm Cache and Reinstall Dependencies to Fix npm Install Errors
Learn how to clear npm cache, delete node_modules, and reinstall dependencies to fix npm install errors. Step-by-step guide with commands.
XPath Cheat Sheet With Examples, Syntax, Selectors, and Functions
Learn XPath syntax, selectors, functions, and axes with clear examples. Complete XPath cheat sheet for Selenium testing, web scraping, and DOM parsing.
