Trigger an event on route change in Vue | VueJS

featured Image

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

featured Image

How to add common header and footer in vuejs.

Here, in this article, we will learn how to add a common header and footer component in our vuejs application. In general, we always have the same header and footer…

Read more
featured Image

How to call a function in VUE template?

Here, we will learn on how to call a function in vue template. First, we have to define the function in the methods. and then we can use an event…

Read more
featured Image

How to redirect to external url in vue

Here, we will learn how to redirect to an external URL in vuejs application. Page Navigation is one of the basic features of a website. It helps us to navigate…

Read more

Leave a Reply

Your email address will not be published. Required fields are marked *