Detect Route Changes in Vue.js

In Vue.js, you can detect route changes using the Vue Router. Vue Router provides a navigation guard called beforeEach, which allows you to execute some logic before each route navigation.

Here's how you can detect route changes:

  1. Import Vue Router: First, make sure you have Vue Router installed and imported into your project.
  2. Use beforeEach Navigation Guard: Utilize the beforeEach navigation guard to execute logic before each route navigation.

1. Install and setup the Vue Router

First, make sure you have Vue Router installed in your Vue.js project. If not, you can install it via npm or yarn.

npm install vue-router
# or
yarn add vue-router

Then, set up Vue Router in your main JavaScript file, typically main.js.

import Vue from 'vue';
import VueRouter from 'vue-router';
import App from './App.vue';

Vue.use(VueRouter);

const router = new VueRouter({
  routes: [
    // Define your routes here
  ]
});

new Vue({
  router,
  render: h => h(App)
}).$mount('#app');

2. Detect Route Changes

Once the Vue Router is set up, you can detect route changes by adding a navigation guard.

router.beforeEach((to, from, next) => {
  // This function will be called before each route change
  console.log('Navigating from', from.fullPath, 'to', to.fullPath);
  
  // You can perform any additional logic here
  
  // Make sure to call next() to continue with the navigation
  next();
});

In this code snippet

  • to is the route object for the route being navigated.
  • from is the route object for the route being navigated away from?
  • next is a function that must be called to resolve the hook. It can be called with or without an argument.

Example

Let's say you have two routes, /home and /about. Here's how you can detect route changes.

// Define routes
const routes = [
  { path: '/home', component: HomeComponent },
  { path: '/about', component: AboutComponent }
];

// Create router instance
const router = new VueRouter({
  routes
});

// Navigation guard to detect route changes
router.beforeEach((to, from, next) => {
  console.log('Navigating from', from.fullPath, 'to', to.fullPath);
  next(); // Continue with the navigation
});

Now, whenever the user navigates between /home and /about, you'll see corresponding log messages in the console.

That's how you can detect route changes in Vue.js using Vue Router.