Vue Router: Make your application routeable!

Front-end development engineer (main job), technical blogger (side job), passed CET6
Ashan and her cat_CSDN personal homepage
Senior topic writer at Niuke, creating a high-quality column “Essentials for Front-end Interviews” at Niuke
The contracted author of Lanqiao Cloud Class, the front-end and back-end practical courses “Vue.js and Egg.js Develop Enterprise-level Health Management Projects” and “Take you to fully master uni-app from entry to practice” have been launched on Lanqiao Cloud Class

Article directory

    • 1. Route navigation
    • 2. Nested routing
    • 3. Routing parameters
    • 4. Routing transition
    • 5. Navigation Guard
    • 6. Routing status management

Vue Router is the official routing manager of Vue.js. It provides a mechanism to implement the routing function of single page applications (SPA). The main functions include:

1. Route navigation

Vue Router allows you to define different routes in your application and jump to the corresponding route based on the user’s navigation operations. It responds to navigation operations by listening for changes in the URL and can route jumps programmatically.

When using Vue Router, you can use the following code example to demonstrate how to define routes, listen for navigation operations, and perform programmatic route jumps:

First, install and import Vue Router:

npm install vue-router
import Vue from 'vue';
import VueRouter from 'vue-router';

Vue.use(VueRouter);

Then, define the routing component:

// Home.vue
<template>
  <div>
    <h2>Home</h2>
    <p>Welcome to the home page!</p>
  </div>
</template>

// About.vue
<template>
  <div>
    <h2>About</h2>
    <p>This is the about page.</p>
  </div>
</template>

Next, create a Vue Router instance and configure routing:

const routes = [
  {<!-- -->
    path: '/',
    component:Home
  },
  {<!-- -->
    path: '/about',
    component: About
  }
];

const router = new VueRouter({<!-- -->
  routes
});

Use in the Vue root instance to render the matching component:

new Vue({<!-- -->
  router,
  el: '#app'
});
<!-- App.vue -->
<template>
  <div id="app">
    <h1>My App</h1>
    <router-view></router-view>
  </div>
</template>

Now, you can trigger route jumps based on user navigation operations, or use programmatic navigation:

// Monitor navigation operations
router.beforeEach((to, from, next) => {<!-- -->
  //Do some logical processing of navigation guards
  next();
});

// Programmatic route jump
// Use the $router.push method to jump to the specified route
router.push('/about');

Through the above code examples, you can better understand how to use Vue Router, and implement the function of defining different routes in the application and performing route jumps based on the user’s navigation operations.

2. Nested routing

Vue Router supports nested routing, and sub-routes can be defined under a parent route. This makes it easy to implement hierarchical nesting and organization of pages, making the routing structure of the application clearer and more maintainable.

When using Vue Router to implement nested routing, the following code example can be used to demonstrate how to define the nesting and organization of parent-child routing:

First, define the components of the parent route and child route:

// Parent.vue
<template>
  <div>
    <h2>Parent</h2>
    <p>This is the parent page.</p>
    <router-view></router-view>
  </div>
</template>

// Child.vue
<template>
  <div>
    <h3>Child</h3>
    <p>This is the child page.</p>
  </div>
</template>

Next, create a Vue Router instance and configure parent-child routing:

const routes = [
  {<!-- -->
    path: '/',
    component: Parent,
    children: [
      {<!-- -->
        path: '',
        component: Child
      },
      {<!-- -->
        path: 'child',
        component: Child
      }
    ]
  }
];

const router = new VueRouter({<!-- -->
  routes
});

Use the tag in the parent routing component to render child routes:

<template>
  <div>
    <h2>Parent</h2>
    <p>This is the parent page.</p>
    <router-view></router-view>
  </div>
</template>

Now, when accessing the parent route, the components of the child route will be rendered into the of the parent route component, forming the effect of nested routing.

For example, when accessing the / path, the parent routing component will render, and at the same time render the child routing component to the parent routing component’s . When accessing the /child path, the parent routing component will also be rendered, but the child routing component will be rendered according to the routing configuration.

Through the above code examples, you can create nesting and organization of parent-child routes in Vue Router, making the routing structure of the application clearer and maintainable.

3. Routing parameters

Vue Router allows defining routing parameters, so that parameters can be passed in routing to achieve the effect of dynamic routing. Parameters can be passed through URL paths, query strings, or routing configuration items to achieve dynamic rendering and data display of corresponding components.

When using Vue Router to define routing parameters, the following code example can be used to demonstrate how to pass parameters and obtain parameters in components:

First, define the route with parameters:

const routes = [
  {<!-- -->
    path: '/user/:id',
    component: User
  }
];

In the above code, :id is the path parameter and different values can be passed in the route, such as /user/1 or /user/2.

Then, pass $route.params in the component to get the passed parameters:

<template>
  <div>
    <h2>User Profile</h2>
    <p>User ID: {<!-- -->{ $route.params.id }}</p>
  </div>
</template>

<script>
export default {
  mounted() {
    const id = this.$route.params.id;
    //Do some logical processing based on the passed parameters
  }
};
</script>

Use $route.params.id to obtain the parameters passed in the route and perform dynamic rendering and data display of the corresponding components.

Alternatively, you can specify query string parameters when defining the route:

const routes = [
  {<!-- -->
    path: '/user',
    component: User,
    props: (route) => ({<!-- -->
      query: route.query
    })
  }
];

In the above code, route.query is the query string parameter that can be passed in the URL, such as /user?id=1 & name=John.

Then, in the component you can use props to receive query string parameters:

<template>
  <div>
    <h2>User Profile</h2>
    <p>User ID: {<!-- -->{ query.id }}</p>
    <p>User Name: {<!-- -->{ query.name }}</p>
  </div>
</template>

<script>
export default {
  props: ['query']
};
</script>

Through the above code, you can define routing parameters in Vue Router and obtain path parameters or query string parameters in the component to achieve the effect of dynamic routing, dynamic rendering of components and data display.

4. Routing transition

Vue Router provides built-in support for transition effects when switching pages. By configuring the transition effect of routing, you can achieve smooth transition and animation effects between pages to improve user experience.

When using Vue Router to provide transition effects when switching pages, you can use the following code example to demonstrate how to configure route transition effects:

First, define the component to which the transition effect needs to be applied:

// Home.vue
<template>
  <div>
    <h2>Home</h2>
    <p>Welcome to the home page!</p>
  </div>
</template>

// About.vue
<template>
  <div>
    <h2>About</h2>
    <p>About us</p>
  </div>
</template>

Next, use to wrap the content in the component and specify the CSS class name of the transition effect:

<template>
  <transition name="fade">
    <div>
      <!-- Component content -->
    </div>
  </transition>
</template>

<style>
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s;
}

.fade-enter,
.fade-leave-to {
  opacity: 0;
}
</style>

In the above code, we use the transition effect class name named “fade” and define the transition animation effect through CSS.

Finally, add the name of the transition effect to the route in the routing configuration:

const routes = [
  {<!-- -->
    path: '/',
    component:Home
  },
  {<!-- -->
    path: '/about',
    component: About
  }
];

In the above code, when switching to the / path, the Home component is loaded and the transition effect is applied.

5. Navigation Guard

Vue Router provides the navigation guard function, which can intercept and process navigation operations during route navigation. Through navigation guards, logic processing such as data loading, permission verification, and jump cancellation can be implemented before and after routing switching.

When using Vue Router’s navigation guard, you can use the following code example to demonstrate how to intercept and handle route navigation:

First, define the callback function of the navigation guard:

const router = new VueRouter({<!-- -->
  routes: [...],
});

router.beforeEach((to, from, next) => {<!-- -->
  // Process logic before routing switching
  //Can perform data loading, permission verification and other operations

  next(); // Call next() to continue routing navigation
});

In the above code, beforeEach is a global pre-guard, and the callback function will be executed before each route switch. The to parameter represents the target route to be navigated to, and the from parameter represents the source route of the current navigation.

In the callback function, some logical processing can be performed, such as data loading, permission verification, etc. It should be noted that if you want to continue route navigation, you need to call next().

You can also define global post guards and guards within components:

router.afterEach((to, from) => {<!-- -->
  // Process logic after routing switch
});

const routes = [
  {<!-- -->
    path: '/user/:id',
    component: User,
    beforeEnter: (to, from, next) => {<!-- -->
      // Process logic before entering routing
      next(); // Call next() to continue routing navigation
    }
  }
];

afterEach in the above code is a global post guard that will be executed after each routing switch. And beforeEnter is the route exclusive guard in the routing configuration, which will only be executed before a specific route enters.

By defining the callback function of the navigation guard, interception and processing operations during route navigation can be implemented. In this way, you can load data, verify permissions, cancel jumps, etc. to control the behavior and logic of routing.

6. Routing status management

Vue Router can be seamlessly integrated with Vuex (the state management library of Vue.js), and can perform state management during the routing navigation process to achieve data sharing and state transfer between different routes.

When using Vue Router to integrate with Vuex, you can use the following code example to demonstrate how to manage state during route navigation:

First, create a Vuex store and define the state that needs to be shared and managed:

// store.js
import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

const store = new Vuex.Store({<!-- -->
  state: {<!-- -->
    user: null // User information
  },
  mutations: {<!-- -->
    setUser(state, user) {<!-- -->
      state.user = user;
    }
  }
});

export default store;

In the above code, we create a Vuex store containing the user state and define a mutation named setUser to update user The value of the status.

Next, use Vuex for state management during the route navigation process. You can call Vuex’s mutation in the callback function of the navigation guard to update the state:

// main.js
import Vue from 'vue';
import App from './App.vue';
import router from './router';
import store from './store';

Vue.config.productionTip = false;

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

In the above code, we pass the Vuex store object to the Vue instance so that it can be accessed and used throughout the application.

Update the state of the Vuex store in the navigation guard’s callback function:

router.beforeEach((to, from, next) => {<!-- -->
  // Process logic before routing switching
  //Can perform data loading, permission verification and other operations
  const user = // Logic for obtaining user information, such as obtaining user data from the backend

  store.commit('setUser', user); // Call Vuex's mutation to update the status

  next(); // Call next() to continue routing navigation
});

In the above code, we obtain the user information in the navigation guard’s callback function and update the user state by calling Vuex’s setUser mutation.

Access Vuex store state in other components:

// MyComponent.vue
export default {<!-- -->
  computed: {<!-- -->
    user() {<!-- -->
      return this.$store.state.user; // Access the state of the Vuex store
    }
  }
};

In the above code, we use the computed property user to access the user state in the Vuex store.

Through the above code examples, Vuex can be used for state management during the routing navigation process to achieve data sharing and state transfer between different routes. This can simplify application data transfer and management and improve development efficiency.

Through the above functions, Vue Router provides a convenient way to manage the routing of front-end applications, allowing developers to better organize and manage different pages and components of the application, and achieve a good user navigation experience.