Categories
Vue Answers

How to listen for route change events with Vue.js and Vue Router?

Spread the love

Sometimes, we want to listen for route change events with Vue.js and Vue Router.

In this article, we’ll look at how to listen for route change events with Vue.js and Vue Router.

How to listen for route change events with Vue.js and Vue Router?

To listen for route change events with Vue.js and Vue Router, we can watch the $route object in our component.

For instance, we write

<template>
  <div>...</div>
</template>

<script>
//...
export default {
  //...
  watch: {
    $route: {
      deep: true,
      handler(to, from) {
        this.show = false;
      },
    },
  },
  //...
};
</script>

to watch the $route in our component.

We set deep to true to watch for all changes in the $route object’s contents.

to has the latest route data.

from has the data of the previous route.

Conclusion

To listen for route change events with Vue.js and Vue Router, we can watch the $route object in our component.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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