Detailed explanation of Vue routing router

Detailed explanation of Vue routing router

Using routing plugins in a modular way

(1) Installation

npm install vue-router

(2) Build a file directory

Create a router folder in the src directory and then create an index.js

insert image description here

(3) Here we create routes in a modular way to facilitate code management. Here we only register the route plug-in and then create the route object. The created routing object is exposed through the export default keyword.

//index.js
import VueRouter from 'vue-router'
import Vue from 'vue'
import Home from "../views/Home";
Vue.use(VueRouter) //Register routing plugin export default new VueRouter({
    routes:[{
        path:'/',
        component:Home
    }]
})

(4) Import the created routing object into the entry file main.js and mount it to the Vue instance.

//main.js
import Vue from 'vue'
import App from './App.vue'
import store from '@/store'
import router from '@/router' //Here we introduce the routing object we created. Modular programming thinking Vue.config.productionTip = false
Vue.prototype.bus = new Vue()
new Vue({
  store,
  router,
  render: h => h(App),
}).$mount('#app')

Using Routes

Declarative navigation

It can be understood that jumping through labels

Declarative navigation: <router-link :to="..."> or <router-link to="...">

Defining routing rules

 {
        path:'/',
        component:Home
        name:home
    }

(1) The to attribute of the router-link navigation tag uses a string

 <router-link to="/">go to home</router-link>

(2) How to use the router-link navigation tag to object

Matching using paths

 <router-link :to="{path:'/'}">go to home</router-link>

The router-link navigation tag to attribute uses an object and matches the route name

 <router-link :to="{name:'home'}">go to home</router-link>

Programmatic navigation

It can be understood as JS jump

Programmatic navigation: router.push(...)

The following example contains knowledge about dynamic route matching and query parameters. If you are not clear about it, you can read the contents of these two first and then come back to read the content here.

// string router.push('home')
// Object router.push({ path: 'home' })
// Named routes router.push({ name: 'user', params: { userId: '123' }})
// With query parameters, becomes /register?plan=private
router.push({ path: 'register', query: { plan: 'private' }})

Note : If path is provided, params will be ignored, which is not the case for query in the above example. Instead, you need to provide the route name and params or write the complete path with parameters manually:

const userId = '123'
router.push({ name: 'user', params: { userId }}) // -> /user/123
router.push({ path: `/user/${userId}` }) // -> /user/123
// The params here are not effective router.push({ path: '/user', params: { userId }}) // -> /user

Dynamic route matching

Defining routing rules

 {
        path:'/user/:id',
        component:User
        name:user
    }
 <router-link to="/user/01">go to home</router-link>
 <router-link :to="{path:'/user/01'}">go to home</router-link>
 <router-link :to="{name:'/user',params={id:'01'}}">go to home</router-link>

By defining it as above, you can get the dynamic route parameters through $route.params.id: the id value is '01'

Notice:

When using the object method for matching, path and params cannot be used. Only by name and params

The following method cannot match the routing rule {path:'/user/:id'}. The following expression can only be understood as '/user'.

Even if the route is matched by the * wildcard, params will not be passed, because the params attribute will not be parsed if the path attribute is present.

{
  // Will match all paths path: '*'
}
{
  // Will match any path starting with `/user-` path: '/user-*'
}

Wildcard matching path

We usually use * to capture other unexpected paths and handle them as a fallback, usually navigating them to a 404 error page.

<router-link to="/user?name=zhangsan">...</router-link>
<router-link :to="{path:'/user?zhangsan'}">...</router-link>
<router-link :to="{path:'/user',query:{name:'zhangsan'}}">...</router-link>
<router-link :to="{name:'user',query:{name:'zhangsan'}}">...</router-link>

When a wildcard is used, a parameter called pathMatch is automatically added to $route.params. It contains the part of the URL that is matched by the wildcard

Query parameters

<router-link to="/user?name=zhangsan">...</router-link>
<router-link :to="{path:'/user?zhangsan'}">...</router-link>
<router-link :to="{path:'/user',query:{name:'zhangsan'}}">...</router-link>
<router-link :to="{name:'user',query:{name:'zhangsan'}}">...</router-link>

Query parameters are not like dynamic route parameter matching. Even if path is used, query can still be used to pass parameters;

The parameters passed by the above query can be obtained through this.$route.query.name .

Responding to changes in routing parameters

If the route is navigated from /user/01 to /user/02 , the original component instance will be reused. Since both routes render the same component, this means that the component's lifecycle hooks will not be called again. Therefore, it is necessary to respond to changes in monitoring parameters in other ways.

(1) Monitoring through watch

const User = {
  template: '...',
  watch:
    $route(to, from) {
      // Respond to route changes...
    }
  }
}

(2) Monitoring through navigation guards

const User = {
  template: '...',
  beforeRouteUpdate(to, from, next) {
    // react to route changes...
    // don't forget to call next()
  }
}

Named routes, route aliases, and redirects

In particular, I put these three concepts together to explain in order to better distinguish the differences between them. These contents are configured in the routing rules .

{
        path: '/pageOne',
        component:PageOne,
        alias:"/firstPage",
        name:"pageOne",
        redirect:{name:'pageTwo'}
    },
    {
        path: '/pageTwo',
        component:PageTwo,
        name:'pageTwo'
    }

(1) Naming the route: This can be understood as giving this route a name

Even if you give the route a name through the name attribute

routes: [
    {
      path: '/user/:userId',
      name: 'user',
      component: User
    }
  ]

(2) Route alias: It can be understood as the second name of this route.

For example, the alias of /a is /b. When a user visits /b, the URL will remain /b but the content matched by the route will be /a. That is, the knowledge URL content shows that the content of /b is actually /a.

Note: the alias here should be expressed as a path, rather than directly writing the name like named routes~

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

(3) Redirection: It can be understood as directly jumping to /b when accessing /a

There are three forms of redirection statements:

  • String
const router = new VueRouter({
  routes: [
    { path: '/a', redirect: '/b' }
  ]
})
  • Object
const router = new VueRouter({
  routes: [
    { path: '/a', redirect: { name: 'foo' }}
  ]
})
  • method
const router = new VueRouter({
  routes: [
    { path: '/a', redirect: to => {
      // Method receives the target route as a parameter // return the redirected string path/path object }}
  ]
})

Nested Routes

Nested routing can be understood in this way. The components rendered by the matched routes contain routing components. When we match a route, '/user' renders a component User, but if we want to continue matching in the <router-view ></router-view> of the User component. Then we need to further match by /user/childRouteName. "childRouteName" is the value of the corresponding path in our routing rule children.

 {
      path: '/user',
      component: User,
      children: [
        {
          // When /user//profile matches successfully,
          // UserProfile will be rendered in User's <router-view> path: 'profile',
          component: UserProfile
        },
        {
          // When /user//posts matches successfully // UserPosts will be rendered in User's <router-view> path: 'posts',
          component: UserPosts
        }
      ]
    }

APP.Vue

<div id="app">
  <router-view></router-view>
</div>

In the User component

const User = {
  template: `
    <div class="user">
      <span>User Component</span>
      <router-view></router-view>
    </div>
  `
}

Notice:

When nested routes are defined, that is, when children are defined, the route must be complete to match correctly. That is, when /user/profile is matched successfully, /user will not be matched successfully.

Named Views

When rendering multiple views on a component at the same time, pay attention to displaying multiple views at the same level, rather than nesting them. At this time, you can solve this problem by naming the view.
Routing rule definition

{
        path:"/namingRoute",
        components:{//Note that components ends with 's', which was not the case when used alone.
            default:Home,
            one:PageOne,
            two:PageTwo
        }
    }

Component Definition

 	<router-view></router-view>//Render the component corresponding to default<router-view name="one"></router-view>//Render the component corresponding to one<router-view name="two"></router-view>//Render the component corresponding to two

When the URL is :/namingRoute and the route is matched, it will be rendered according to the corresponding router-view component.

Navigation Guard

(1) Global Guard

It can be understood as a guard defined by the global router instance object router.

  • route.beforeEach (global before guard)

Directions:

beforeEach((to,from,next)=>{
	//...
})
  • router.beforeResolve (global resolution guard)

After all guards in components and async route components are resolved, the resolve guard is called

Directions:

router.beforeResolve((to, from, next) => {
  // ...
})
  • router.afterEach (global after hook)

The hook does not accept a next function and does not alter the navigation itself:

Directions:

router.afterEach((to, from) => {
  // ...
})
Location used: usually index.js in the router folder
const router = new VueRouter({ ... })
//Global front guard router.beforeEach((to, from, next) => {
  // ...
})
//Global resolution guard router.beforeResolve((to, from, next) => {
  // ...
})
//Global post-hook router.afterEach((to, from) => {
  // ...
})

(2) Exclusive router guard

It can be understood as a guard defined in the routing rules

  • beforeEnter

(3) Guarding within components

It can be understood as a guard defined in the component

  • beforeRouteEnter

The component instance has not been created yet. Called before the route is confirmed.

const User = {
  template: `...`,
  beforeRouteEnter(to, from, next) {
    // Called before the corresponding route that renders this component is confirmed // No! able! Get the component instance `this`
    // Because the component instance has not been created before the guard is executed}
}

Notice:

The guard cannot directly use this to access the vue instance object because the component instance has not been created yet. However, you can pass a callback to the next method to locate the component instance.

Passing a callback to next() is only valid when used in beforeRouteEnter! ! !

beforeRouteEnter (to, from, next) {
  next(vm => {
    // Access the component instance via `vm`})
}
  • beforeRouteUpdate (new in 2.2)

Called when the route changes and the component is used

const User = {
  template: `...`,
  beforeRouteUpdate(to, from, next) {
    // Called when the current route changes but the component is reused // For example, for a path /foo/:id with dynamic parameters, when jumping between /foo/1 and /foo/2,
    // Since the same Foo component will be rendered, the component instance will be reused. And this hook will be called in this case.
    // You can access the component instance `this`
  }
}
  • beforeRouteLeave

Called when the navigation leaves the route corresponding to this component

const User = {
  template: `...`,
  beforeRouteLeave(to, from, next) {
    // Called when navigating away from the corresponding route of this component // You can access the component instance `this`
  }
}

Navigation analysis process

Normal execution order for first access routes

  • beforeEach global routing front guard
  • beforeEnter exclusive route guard
  • beforeRouteEnter component routing guard
  • beforeResolve global routing resolution guard
  • afterEach global routing post-hook
  • Dom Rendering
  • Calls the callback function passed to next in the beforeRouteEnter component routing guard. And pass the created component instance as a parameter of the callback function.

Summarize

This article ends here. I hope it can be helpful to you. I also hope you can pay more attention to more content on 123WORDPRESS.COM!

You may also be interested in:
  • Detailed explanation of Vue-router nested routing
  • vue.js Router nested routes
  • Detailed explanation of the two modes of Router routing in Vue: hash and history
  • Implementation of nested jump of vue routing view router-view
  • Detailed explanation of VueRouter routing
  • Detailed explanation of Vue router routing

<<:  A complete example of mysql querying batch data from one table and inserting it into another table

>>:  HTML table tag tutorial (26): cell tag

Recommend

Django uses pillow to simply set up verification code function (python)

1. Import the module and define a validation stat...

Screen command and usage in Linux

Screen Introduction Screen is a free software dev...

How to prevent computer slowdown when WIN10 has multiple databases installed

Enable the service when you need it, and disable ...

Explore how an LED can get you started with the Linux kernel

Table of contents Preface LED Trigger Start explo...

Vue realizes cascading selection of provinces, cities and districts

Recently, I need to implement a cascading selecti...

MySQL 5.7.18 zip version installation tutorial

The mysql 5.7.18 zip version of MySQL is not like...

A summary of detailed insights on how to import CSS

The development history of CSS will not be introd...

Circular progress bar implemented with CSS

Achieve results Implementation Code html <div ...

Two ways to exit bash in docker container under Linux

If you want to exit bash, there are two options: ...

Detailed explanation of CSS3+JS perfect implementation of magnifying glass mode

About a year ago, I wrote an article: Analysis of...

Implementation of form submission in html

Form submission code 1. Source code analysis <...

Mybatis paging plug-in pageHelper detailed explanation and simple example

Mybatis paging plug-in pageHelper detailed explan...

Vue implements bottom query function

This article example shares the specific code of ...