SoFunction
Updated on 2025-04-04

Detailed explanation of the introduction and use of vue-router in vue2

1. Introduction

Vue is very suitable for building single-page applications. For most such applications, it is recommended to use the officially supported Vue Router; in a Single-page application, the client's JavaScript can intercept page redirect requests, dynamically obtain new data, and then update the current page without reloading. This can usually lead to a smoother user experience, because in this kind of scenarios, users will usually interact multiple times over a long period of time. In this type of single-page application, the route update is executed on the client.

Vue Router is the official route of Vue. It is deeply integrated with the core, making it easy to build a single page application with it. Functions include:

  • Nested routing mapping
  • Dynamic routing
  • Modular, component-based routing configuration
  • Routing parameters, queries, wildcards
  • Shows the transition effect provided by the transition system
  • Detailed navigation control
  • Automatically activate links to CSS classes
  • HTML5 history pattern or hash pattern
  • Customizable scrolling behavior
  • Correct encoding of URL

Let's introduce the basic use of Vue Router. This article is written based on vue2 and [email protected].

Use of Router

2.1 Installation

For vue2, we recommend using the vue-router version. If it is greater than, some functions cannot be introduced and used normally in vue2.

The node environment is installed as follows:

npm install [email protected]

2.2 Project introduction and use

In our engineering projects, routing files usually need to be managed separately for subsequent use and maintenance. Based on this, we introduce it into two steps:

  • Create a unified management route entry file
  • Vue project introduction using routing entry files

2.2.1 Create a routing file

Create a router folder in the same level as the file and add the file (using ts, the same applies if using js).

The file contents are as follows:

import Vue from "vue";
import VueRouter from "vue-router";
import routers from "./practice/practice";
import echartsRouters from './practice/echarts'

// Register all components in vue-router(VueRouter);

const allRouter = [...routers, ...echartsRouters];
const router = new VueRouter({
  mode: "history",
  routes: allRouter
});

export default router;

(VueRouter) is to register all components for convenience of global use, such as routerview, etc.

2.2.2 Introduction

The code is as follows:

import Vue from "vue";
import App from "./";
import "./registerServiceWorker";
import router from "./router";
import store from "./store";

 = false;

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

2.2.3 Configuration

<template>
  <div >
    <router-view></router-view>
  </div>
</template>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

2.3 Overall directory structure

├── public/
├── src/
│   ├── assets/                                                                                                                                                             �
│   │   ├── fonts/
│   │   └── images/
│   │
│   ├── components/
│   │   └── UserSelectTable/
│   │       ├── style/
│   │       │   ├── _var.scss
│   │       │   └──
│   │       ├──
│   │       └──
│   │
│   ├── store/                                                                                                                                                             �
│   │   ├── plugins/
│   │   │   ├──
│   │   │   └──
│   │   ├── modules/                                             # Unless the business is too complicated, it is not recommended
│   │   │   ├──
│   │   │   └──
│   │   ├──
│   │   ├──
│   │   ├──
│   │   └──
│   │
│   ├── router/
│   │   ├──
│   │   └──
│   │
│   ├── views/                                                                                                                                                             �
│   │   ├── Home/
│   │   │   ├── components/
│   │   │   ├── services/                     # Page-level group data request
│   │   │   │   └──
│   │   │   └──
│   │   │
│   │   └── About/
│   │       ├── components/
│   │       └──  
│   │
│   └──

├── .browserslistrc
├── .env
├── .editorconfig
├── .
├── .prettierrc
├──
├──
├──                       
└──

2.4 How to use

After the introduction of router, we can use the router's own components to perform routing management to facilitate routing access and unified management of large projects. The following introduces several commonly used uses.

2.4.1 Use router-view to switch page view

After entering, our single-page application can use router-view to switch pages in configuration and perform nested routing configuration. After introduction, in the Vue instance, you can access the routing instance through $router. If you want to navigate to a different URL, use this.$(...) to jump.

Nested routing cases are as follows:

	{
      path: '/user',
      component: User,
      children: [
        {
          // When accessing /user/profile,          // The page component UserProfile will be rendered in the <router-view> of User          path: 'profile',
          component: UserProfile
        },
        {
          // When accessing /user/posts          // Page component UserPosts will be rendered in User's <router-view>          path: 'posts',
          component: UserPosts
        }
      ]
    }

The detailed router-view usage method can be seenDetailed explanation of using vue router-view

2.4.2 Use router-link to jump page

When using <router-link>, the method (...) will be called internally, so clicking <router-link :to="..."> is equivalent to calling (...)

<router-link :to="{ name: 'user', params: { userId: '12345678' }}">User</router-link>

2.4.3 Routing redirection

Adding the redirect attribute when defining a route can realize redirection, as shown below:

routes: [
    { path: '/a', redirect: '/b' }
  ]

In this case, when accessing route a, it will automatically redirect to b. It is usually very useful when doing abandoned page transformations

2.4.4 Routing parameters

When the page is redirected, you can add parameters to the push method. Different routing access methods and parameter transfer methods are different;

  • When using path jump, the route passes the parameter through query;
  • When using name jump, the route parameter is passed through params’;

The path and name here are the key values ​​corresponding to our routing file; as follows:

 {
    path: "/productList",
    name: "productList",
    component: () => import("@/views/productList/")
  },

The code to route arguments using path and name is as follows:

path route parameter transfer

//Path jump corresponding to query method to pass parametersthis.$({
 path: '/routerJump',
  query: {
    name: 'sam', 
    stuNo: '1234'
  }
})

Take parameters on the next page:

// Use query to get parameters = this.$;

Name routing parameter transfer

// // Name jump corresponding to params method to pass parametersthis.$({
 name: 'routerJump',
  params: {
    name: 'sam', 
    stuNo: '1234'
  }
})

Take parameters on the next page:

// Use params to get parameters = this.$;

Note that the route in the $route used when taking parameters does not have "r".

2.4.5 Router Guard

1. Pre-guard for route loading:

((to, from, next) => {
  // ...
})

Each guard method receives three parameters:

to: Route: The target route to be entered

from: Route: The route that the current navigation is about to leave

next: Function: Be sure to call this method to resolve the hook. The execution effect depends on the calling parameters of the next method.

  • next(): performs the next hook in the pipeline. If all hooks are executed, the navigation status is confirmed (confirmed).
  • next(false): interrupts the current navigation. If the browser's URL has changed (maybe it's manual or the browser's back button), the URL address will be reset to the corresponding address from route.
  • next('/') or next({ path: '/' }): Jump to a different address. The current navigation is interrupted and a new navigation is performed. You can pass objects anywhere to next and allow options such as replace: true, name: 'home' and any options used in router-link to prop or .
  • next(error): (2.4.0+) If the parameter passed in next is an Error instance, the navigation will be terminated and the error will be passed to the registered callback of () .

Make sure that the next function is strictly called once in any given navigation guard. It can occur more than once, but only in all logical paths

In case of overlap, otherwise the hook will never be parsed or reported an error.

Use case: Login authentication successfully jumps, otherwise it will not jump:

((to, from, next) => {
  if ( !== 'Login' && !isAuthenticated) next({ name: 'Login' })
  else next()
})

2. Router jump rear hook

The difference between back hooks and guards is that these hooks do not accept the next function and do not change the navigation itself:

((to, from) => {
  // ...
})

3. Guards within components

In actual situations, we use more guards within the component, and directly define the following route navigation guards within the routing component:

  • beforeRouteEnter
  • beforeRouteUpdate (2.2 new)
  • beforeRouteLeave

Pay attention to the access and processing of this during the life cycle, and the specific use is as follows:

  template: `...`,
  beforeRouteEnter(to, from, next) {
    // Called before rendering the corresponding route of the component is confirmed    // No!  able!  Get component instance `this`    // Because the component instance has not been created before the guard has been executed  },
  beforeRouteUpdate(to, from, next) {
    // Called when the current route changes but the component is reused    // For example, for a path with dynamic parameters /foo/:id, when jumping between /foo/1 and /foo/2,    // Since the same Foo component is rendered, component instances are reused.  And this hook will be called in this case.    // Component instances can be accessed `this`  },
  beforeRouteLeave(to, from, next) {
    // Called when navigation leaves the corresponding route of this component    // Component instances can be accessed `this`  }

3. Others

This article introduces the most used in actual developmentVue RouterBuilt-in components, making good use of these components can often simplify some complex problems and make project development easy. In addition, this article refers to the official website for the actual operation of vue2 routing configuration. For more comprehensive use, please refer to the official website.vue router

The above is the detailed explanation of the introduction and use of vue-router in vue2. For more information about vue2 vue-router, please follow my other related articles!