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?

Scroll to Top