SoFunction
Updated on 2025-04-05

A super detailed Vue-Router step-by-step tutorial

Recently, I was revisiting the Vue Family Bucket. I felt that I remember it more deeply, so I specifically recorded it (the vue-router version of this article is).

1,router-view

<router-view> is a functional component that renders the view component to which paths match. Can be used with <transition> and <keep-alive>. If you use both together, make sure to use <keep-alive> on the inner layer.

&lt;router-view&gt;&lt;/router-view&gt;
&lt;!--or--&gt;
&lt;router-view name="footer"&gt;&lt;/router-view&gt;

If the <router-view> has a name set, the corresponding component under components in the corresponding routing configuration will be rendered.

2,router-link

The <router-link> tag supports users to navigate in applications with routing capabilities (clicks).

property type illustrate
to String/Object Target routing/Objects at the target location
replace Boolean No navigation records left
append Boolean Add path /a => /a/b after the current path
tag String Specify what kind of label to render
active-class String Class used when activated
<router-link :to="{ path: '/login'}" replace tag="span"></router-link>

3. Redirect redirect

Root route redirects to login

const router = new VueRouter({
  routes: [
    { path: '/', redirect: '/login' }
  ]
})

Dynamically return to the redirect target

const router = new VueRouter({
  routes: [
    { path: '/a', redirect: to =&gt; {
      // Method reception Target routing as parameter      // return redirected string path/path object    }}
  ]
})

4. Routing alias

When a route accesses /b, the URL will remain as /b, but the route matches /a

const router = new VueRouter({
  routes: [
    { path: '/a', component: A, alias: '/b' }
  ]
})

5. Routing parameters props

Use props to avoid overcoupling with $route, so that you can directly use props to receive parameters in the component

5.1, Boolean mode

Write parameters after the route and set props to true

{
 path: '/vuex/:id',
 name: 'Vuex',
 component: () => import('@/view/vuex'),
 props: true,
 mate: {
  title: 'vuex'
 }
}

Set the parameters that need to be passed by jump

&lt;router-link :to="{name:'Vuex', params: {id: '99999'}}" tag="h1"&gt;Jump&lt;/router-link&gt;
&lt;!--or--&gt;
toNext() {
    this.$({
     name: 'Vuex',
     params: {
      id: '99999'
     }
    })
}

On the page that jumps past, take the argument through props or this.$params

props: {
 id: {
  type: String,
  default: ''
 }
}
&lt;!--or--&gt;
this.$

5.2, Object Mode

Set props as an object in the route to carry static data

{
 path: '/vuex',
 name: 'Vuex',
 component: () => import('@/view/vuex'),
 props: {
  id: '99999'
 },
 mate: {
  title: 'vuex'
 }
}

Jump

&lt;router-link :to="{name:'Vuex'}" tag="h1"&gt;Jump&lt;/router-link&gt;
&lt;!--or--&gt;
toNext() {
 this.$({
  name: 'Vuex'
 })
}

On the page that jumps past, take the argument through props or this.$params

props: {
 id: {
  type: String,
  default: ''
 }
}
&lt;!--or--&gt;
this.$

Note: Only applicable to static data

5.3, Function Mode

First set props to Function in the route and return an object. Whether it is query parameter transmission or params parameter transmission, it can be converted to props.

{
 path: '/vuex',
 name: 'Vuex',
 component: () => import('@/view/vuex'),
 props: route => ({
     <!--query-->
  id: ,
  <!--params-->
  age: 
 }),
 mate: {
  title: 'vuex'
 }
}

Jump

&lt;router-link :to="{name:'Vuex',query: {id: '99999'}, params:{age:'20'}}" tag="h1"&gt;Jump&lt;/router-link&gt;
&lt;!--or--&gt;
toNext() {
 this.$({
  name: 'Vuex',
  query: {
   id: '999999'
  },
  params: {
   age: '20'
  }
 })
}

On the page that jumps past, use props or this.$ / this.$ to get the argument

props: {
 id: {
  type: String,
  default: ''
 },
 age: {
  type: String,
  default: ''
 }
}
&lt;!--or--&gt;
this.$
this.$

6. Router Guard

Router guards are mainly used to guard navigation through jump or cancellation.

6.1, Global Front Guard beforeEach

When a navigation is triggered, the global pre-guard is called in the order of creation. The guard is performed asynchronously, and the navigation is waiting until all guards have been parsed.

parameter illustrate
to The target routing object to be entered
from The route that the current navigation is about to leave
next Callback method

Next usage is as follows

grammar illustrate
next() Make the next hook
next(false) Interrupt navigation, if the URL has been changed, reset to the address from
next('/') Interrupt the current jump and go to another address, you can set the routing object
next(error) Navigation terminates and passes error to onError()
const router = new VueRouter({ ... })

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

6.2, Global parsing guard beforeResolve

2.5.0 has been added, similar to beforeEach, the difference is that before navigation is confirmed, and after all components are resolved, the parsing guard is called.

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

6.3, global back hook afterEach

The rear guard will not accept the next function and will not change the navigation itself

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

6.4, router exclusive guard beforeEnter

The exclusive beforeEnter guard can be directly defined on the routing configuration, which is the same as the method parameters of the global front guard.

const router = new VueRouter({
  routes: [
    {
      path: '/foo',
      component: Foo,
      beforeEnter: (to, from, next) => {
        // ...
      }
    }
  ]
})

6.5, Guards within components

  • beforeRouteEnter

The guard cannot access this because the guard is called before navigation confirmation, so the new component that is about to appear has not been created yet. You can access component instances by passing a callback to next. When the navigation is confirmed, the callback is executed and the component instance is used as a parameter to the callback method.

const Footer = {
  template: `...`,
  beforeRouteEnter(to, from, next) {
    next(vm =&gt; {
        // Access component instances through `vm`    })
  }
}
  • beforeRouteUpdate (2.2 new)

When the current route changes, but the component is multiplexed, the component instance can be accessed.

const Foo = {
  template: `...`,
  beforeRouteUpdate(to, from, next) {
     = 
    next()
  }
}
  • beforeRouteLeave

Called when navigation leaves the corresponding route of the component, it is usually used to prohibit the user from suddenly leaving before the modification has been saved. Can be cancelled by next(false).

const Foo = {
  template: `...`,
  beforeRouteLeave(to, from, next) {
    const answer = ('Are you sure you want to leave')
    if (answer) {
        next()
    } else {
        next(false)
    }
  }
}

6.6, complete navigation analysis process

  1. Navigation is triggered.
  2. Call the beforeRouteLeave guard in the inactivated component.
  3. Call the global beforeEach guard.
  4. Call the beforeRouteUpdate guard (2.2+) in the reused component.
  5. Call beforeEnter in the routing configuration.
  6. Resolve asynchronous routing components.
  7. Call beforeRouteEnter in the activated component.
  8. Call the global beforeResolve guard (2.5+).
  9. Navigation is confirmed.
  10. Call the global afterEach hook.
  11. Trigger DOM update.
  12. Call the callback function passed to next in the beforeRouteEnter guard. The created component instance will be passed in as a parameter to the callback function.

7. Routing meta information

When defining a route, you can configure the meta object field to store the corresponding information of each route. Accessed via this.$, or through and accessed in the route guard.

const router = new VueRouter({
  routes: [
    {
  path: '/index',
  name: 'Index',
  component: () =&gt; import('@/view/index'),
  meta: {
   title: 'front page',
   rolu: ['admin', 'boss']
  }
 }
  ]
})

8. Transitional effect

You only need to use the transition tag to wrap the router-view tag. The animation effect can be defined by yourself, refer to the usage of the transition component. You can also use watch to listen for $route changes in the parent component or in the parent component, replace the name attribute of the transition component according to different routes, and achieve different animation effects.

<transition :name="transitionName">
  <router-view></router-view>
</transition>

monitor

watch: {
  '$route' (to, from) {
    const toD = ('/').length
    const fromD = ('/').length
     = toD < fromD ? 'slide-right' : 'slide-left'
  }
}

9. Scrolling behavior

When creating a Router instance, a scrollBehavior method can be provided and to receive to and from routing objects. The third parameter savedPosition is only available when triggered by the browser's forward/back button.

const router = new VueRouter({
 mode: 'hash',
 routes,
 scrollBehavior(to, from, savedPosition) {
  if (savedPosition) {
   return new Promise((resolve, reject) => {
    setTimeout(() => {
     resolve(savedPosition)
    }, 1000)
   })
  } else {
   return { x: 0, y: 0 }
  }
 }
})

10. Complete routing configuration

First import Vue and vue-router, then use router to define a collection of routing information. Each route is an object, and the object has the following properties

property type value
path String Component path information
name String Component naming
component Function Components
mate Object Meta-information
children Object Subroutine
redirect String Redirect
props Boolean/Object/Function Parameter pass

The specific code is as follows:

import Vue from 'vue'
import VueRouter from 'vue-router'
(VueRouter)

const routes = [
 {
  path: '/',
  redirect: '/index'
 },
 {
  path: '/index',
  name: 'Index',
  component: () =&gt; import(/* webpackChunkName: "index" */ '@/view/index'),
  mate: {
   title: 'front page',
   auth: false
  }
 },
 {
  path: '/login',
  name: 'Login',
  component: () =&gt; import(/* webpackChunkName: "login" */ '@/view/login'),
  meta: {
   title: 'Log in',
   auth: false
  },
  children: [
   {
    path: 'children',
    name: 'Children',
    component: () =&gt; import(/* webpackChunkName: "children" */ '@/view/children'),
    mate: {
     title: 'Nested subroutine',
     auth: false
    }
   }
  ]
 }
]

const router = new VueRouter({
 mode: 'hash',
 routes
})

export default router

Note: Nested subroutines must place the <router-view> tag on the nested page.

Summarize

This is all about this article about Vue-Router tutorial. For more related contents of Vue-Router step-by-step tutorials, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!