Vue router routing manager

Routing mechanism

introduce

vue router is a plug-in of vue, which is used to provide routing function.
Through the change of route, the components can be loaded dynamically to achieve the purpose of developing single page program.

Use steps of Vue router

1) Create routing component
2) Configure route mapping: component and path mapping relationship
3) Using routing: through < router link > and < router View >

Basic use

1) Define components

let com1 = {template:`<div>this is com1</div>`}
let com2 = {template:`<div>this is com2</div>`}
let com3 = {template:`<div>this is com3</div>`}

2) Define route
Router is the router object and routes is the route list
Route naming: when configuring a route, specify the name attribute for the route to facilitate route jump in the later stage
Redirect: when the user accesses / a, the URL will be replaced with / B, and then the matching route will be / b
Alias: / A's alias is / A, which means that when the user accesses / A, the URL will remain /, but the route matching will be / A, just as the user accesses / a (Note: alias is the alias of path)

let router = new VueRouter({
        routes: [
          { 
            path: '/a',     // Routing address
            component: com1,// Corresponding components
            name: 'comA',   // Set a name for the route to facilitate jump using name
            redirect: '/b', // redirect
            alias: '/A', // alias
          },
          { path: '/b', component: com2 },
          { path: '/c', component: com3 },
        ]
      })

3) Register routing
In the root instance of vue, register the route

let vm = new Vue({
	el: '#app',
	router
})

4) Use routing

<router-link to="/a">A assembly</router-link>
<router-link to="/b">B assembly</router-link>
<router-link to="/c">C assembly</router-link>
<!--The route viewport is used to load the components corresponding to the route-->
<router-view></router-view>

Dynamic route matching

We often need to map all routes matched to a certain pattern to the same component, and a "path parameter" is marked with a colon. When a route is matched, the parameter value will be set to this.$route.params, which can be used in each component.

1) Statement

let router = new VueRouter({
	routes: [
		// Dynamic routing parameters start with a colon 
		{ 
			path: '/user/:username/:id', 
			component:com1 
		}
	]
})
<router-link to="/user/zhangsan/1001"></router-link>

2) Get the parameters carried by the route (the parameter value will be set to this.$route.params)
/Both / user/zhangsan/1001 and / user/lisi/1002 will map to the same component
When dynamic routing changes occur within a component, vue component instances will be reused instead of being destroyed and re created
When reusing components, if you want to respond to changes in routing parameters, you can simply watch and listen to the $route object, or use the navigation guard inside the component

let com1 = {
    data() {
        return {
            id: null,
            username: null
        }
    },
    template: ``,
    created() {
        // In the created hook function, you can only get the parameters carried at one time, not continuously
        this.id = this.$route.params.id;
        this.username = this.$route.params.username;
    },
    watch() {
        // Using the watch listener, you can continuously monitor the changes of parameters carried in the router object
        $route(to, from) {
            this.id = to.params.id;
            this.username = to.params.username;
        }
    }
}

Nested Route

The outermost layer < router View > is the exit of the top layer, rendering the components matched by the most advanced route.
Similarly, a rendered component can also contain its own nested < router View >.
To render components in nested exits, you need to use the children configuration in the parameters of vueroter

let router = new VueRouter({
    routes: [
        {
            path: '/student',
            component: comStu,
            children: [
                { path: 'grade', component: comGrade },
                { path: 'register', component: comRegister },
            ]
        }
    ]
})
//use:
The first level route corresponds to one router-view
 The secondary route corresponds to one router-view

Programming navigation

1) this.$router.push() adds a record to the history stack
Path jump: this. $router. Push ({path: '/ a'})
Name jump: this. $router. Push ({Name: 'coma'})
Route jump and carry parameters:

//path jump and query are used together
this.$router.push({ path: '/a', query: { username: 'zhangsan' } })
//Use name jump with params
this.$router.push({ name: 'comA', params: { age: 12 } })

Parameter acquisition: in the target component of the jump, as long as you can access $route, you can get the parameters carried by the jump

//For example, in created() of the target component
created(){
	console.log(this.$route.params)
	console.log(this.$route.query)
}

The difference between query parameter passing and params parameter passing is as follows:

1. The query parameter is saved in the url address bar and spliced in the form of query string
2. In terms of security, params is relatively secure. query will be displayed in the address bar, which is easy to cause data leakage
3. When refreshing the page, the data in query will not be affected, while the data in params will disappear directly

2) this.$router.replace() directly replaces the current route and will not generate a new history
3) this.$router.go() internally accepts integers with positive or negative values as parameters. Positive numbers are forward and negative numbers are backward (in History)

Routing mode

Modify routing mode:

let router = new VueRouter({
	// mode: 'hash',
	mode: 'history',  // The mode attribute modifies the routing mode, which defaults to the hash mode
	routes: []
})

Differences between hash routing and history Routing:

  1. The hash route has #, but the history route has no #, and it is more compact
  2. When the enter refresh operation is performed, the hash route will be loaded into the page corresponding to the address bar, while the history route generally reports an Error 404
    (refresh is a network request, and history routing requires back-end support).
  3. hash routing supports lower version browsers, and history routing is a new API in HTML5.
  4. The characteristic of hash is that although it appears in the URL, it is not included in the http request, so it has no impact on the back end. Therefore, changing the hash will not reload the page, so it is also a prerequisite for single page applications.
  5. History uses the browser's history stack. Previously, there were back, forward and go methods. Later, pushState() and replaceState() methods (supported by a specific browser) were added in HTML5. They provide the function of modifying the history. However, when modifying, although the current URL is changed, the browser will not send a request to the back end immediately.

Navigation guard

introduce

As its name suggests, the navigation guard provided by Vue router is mainly used to guard navigation by jumping or canceling
Each guard method receives three parameters: (to,from,next)
to: Route the target route object to be entered
from: Route the route that the current navigation is about to leave
next: Function must call this method to resolve this hook and let the route jump continue

next(): go to the next hook in the pipeline (continue to complete the navigation jump)
next(false): interrupt the current navigation.
next('/') or next({path: '/'}): jump to a specified address

Guards are executed asynchronously, and navigation is waiting until all guards resolve

Guard type

1. Guard inside the assembly
Guard a component

let com1 = {
    data() {
        return {}
    },
    template: ``,
    // Front guard inside the assembly; Intercept before entering the current component
    beforeRouteEnter(to, from, next) {
        //...... Interception operation
        //Manually call the next() method to ensure that the route jump continues
        next();
    },
    // Component internal update guard; Triggered when the route changes in the current component
    beforeRouteUpdate(to, from, next) {
        //...... Interception operation
        //Manually call the next() method to ensure that the route jump continues
        next();
    },
    // Rear guard inside the assembly; Triggered before leaving the current component
    beforeRouteLeave(to, from, next) {
        //...... Interception operation
        //Manually call the next() method to ensure that the route jump continues
        next();
    }
}

2. Global guard
Guard the global routing object, and any route jump or update can be detected

let router = new VueRouter({
    routes: [
        {}
    ]
})
// Global front guard
router.beforeEach((to, from, next) => {
    //...... Interception operation
    next();
    // next(false); 
})
// Global post guard
router.afterEach((to, from) => {
    //... after operation
})

3. Route exclusive guard
Guard a routing record

let router = new VueRouter({
    routes: [
        {
            path: '/a',
            component: com1,
            beforeEnter(to, from, next) {
                //...... Interception operation
                next();
            }
        }
    ]
})

Keywords: Vue.js

Added by Warmach on Thu, 14 Oct 2021 03:46:19 +0300