Chapter 6 Router Topic

一、router-link

1. Without parameters

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

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

2. With parameters

<router-link :to="{name:'home', params: {id:1}}">

// Route configuration path: "/ home /: id" or path: "/ home: id"

The parameters of url are not visible, the parameters will disappear after refresh

<router-link :to="{name:'home', query: {id:1}}">

// The route can not be configured

The parameters in the url are visible, and the parameters will not disappear after refreshing

Second, root. $ Router.push () (called in the function)

1. Without parameters

this.$router.push('/home')

this.$router.push({name:'home'}) this.$router.push({path:'/home'})

2 , Query parameter passing

this.$router.push({name:'home',query: {id:'1'}}) this.$router.push({path:'/home',query: {id:'1'}})

The parameters in the url are visible, and the parameters will not disappear after refreshing

3 , params pass parameter

this.$router.push({name:'home',params: {id:'1'}})

// Route configuration path: "/ home /: id" or path: "/ home: id",

// If the path is not configured , the parameters of refreshing the page will disappear

// Configure path, refresh page id will be retained

4 , Query and params difference

The query jump is matched with the path attribute of the route , the parameter is passed in plain text, the parameters on the url are visible, and the parameters will not disappear after refreshing

Params is used in conjunction with the route name attribute, the parameters are transmitted in cipher text, the parameters on the url are impossible, and the parameters will disappear after refreshing

Three, Router jump, receive parameters

query parameter

root. $ router.push ({ 
  path: ' / select ' ,    // jump path 
  query: {   
    id: this .id,   
  } 
})

Parameter reception: root. $ Route.query.xxxxxxx

Params parameter turn

root. $ router.push ({ 
  name: 'Select ' , // jump path 
  params : { 
    id: this .id,   
  } 
})

Parameter reception: root. $ Route.params.xxxxxxx

The difference between $ router and $ route:

router is an instance of VueRouter , equivalent to a global router object, which contains many attributes and sub-objects .

Route is equivalent to the routing object currently being jumped , and you can get name, path, params, query, etc. from it .

Four, routing guard

1.router.beforeEach ((to, from, next)) before the route jump :

ext: Function: Must call this method to resolve this hook. The execution effect depends on the call parameters of the next method.

next () is executed to the inside of the route object

Proceed to the next hook in the pipeline. If all hooks are executed, the navigation status is confirmed ( confirmed ) .

next(false):

Interrupt the current navigation.

If the URL of the browser changes ( may be the user manually or the browser back button ) , then the URL address will be reset to the address corresponding to the from route.

next ('/') or next ({path: '/'}):

Jump to a different address. The current navigation is interrupted, and then a new navigation is performed. You can the next pass an arbitrary position of an object, such as a set and allows Replace: to true , name: 'Home' option and the like used in any router-link the toprop or router.push the options.

next (error): (2.4.0+) If the next parameter passed is an Error instance, the navigation will be terminated and the error will be passed to the callback registered by router.onError () .

Make sure to call the next method, otherwise the hook will not be resolved .

2. Role ( authorization verification , dynamic routing )

router.beforeEach ((to, from , next) => { 
    NProgress.start () //   Start progress bar 
    if (getToken ()) { // Judge token 
        / * has token * / 
        if (to.path === ' / login ' ) { 
            next ({path: ' / ' }) 
            NProgress.done (); 
        } else { 
             if (store.getters [ ' user / roles ' ] .length === 0 ) { // determine whether the current user User_info information has been pulled
                store.dispatch ( ' user / GetUserInfo ' ) .then (res => { // Pull user_info 
                    const roles = res.data.roles // note: roles must be a array! such as: ['editor', 'develop '] 
                    store.dispatch ( ' permission / GenerateRoutes ' , {roles}). then (() => { // Generate an accessible routing table based on roles permissions 
                        router.addRoutes (store.getters [ " permission / addRouters " ]) // Dynamically add an accessible routing table 
                        next ({... to, replace: true }) // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
                    })
                }).catch((err) => {
                    store.dispatch('FedLogOut').then(() => {
                        Message.error(err)
                        next({ path: '/' })
                    })
                })
            } else {
                next();
            }
} }
else { /* 无 token * / if (whiteList.indexOf (to.path)! ==- 1 ) { // In the login-free whitelist, go directly to next () } else { next (` / login? redirect = $ {to.path}` ) // Otherwise redirect all to the login page NProgress.done () // If it is the login page, you have to deal with it manually }} }) router.afterEach (() => { NProgress.done () // finish progress bar })

Five, dynamic routing

Routes into constantRouterMap and asyncRouterMap groups, routing guard according to the user's authority, to match asyncRouterMap group routes loaded into the router to go :

if (store.getters [ ' user / roles ' ] .length === 0 ) { // Determine whether the current user has finished pulling user_info information 
                store.dispatch ( ' user / GetUserInfo ' ) .then (res => { / / Pull user_info 
                    const roles = res.data.roles // note: roles must be a array! Such as: ['editor', 'develop'] 
                    store.dispatch ( ' permission / GenerateRoutes ' , {roles}). Then (() => { // Generate an accessible routing table based on roles permissions 
                        router.addRoutes (store.getters [ " permission / addRouters "]) // Dynamically add the accessible routing table 
                        next ({... to, replace: true }) // The hack method ensures that addRoutes is completed, set the replace: true so the navigation will not leave a history record 
                    }) 
                }) . catch ((err) => { 
                    store.dispatch ( ' FedLogOut ' ) .then (() => { 
                        Message.error (err) 
                        next ({path: ' / ' }) 
                    }) 
                })

permission/GenerateRoutes方法:

import {asyncRouterMap, constantRouterMap} from  " @ / router " ;
 / * * 
 * Through meta.role to determine whether it matches the current user permissions 
 * @param roles 
 * @param route 
 * / 
function hasPermission (roles, route) { 
    if (route. meta && route.meta.roles) {
         return roles.some ((role) => route.meta.roles.includes (role)); 
    } else {
         return  true ; 
    } 
} 
/ * * 
 * Recursively filter asynchronous routing tables, return Route table in line with user role permissions 
 * @param routes asyncRouterMap 
 * @param roles 
 * /
function filterAsyncRouter(routes, roles) {
    const res = [];
    routes.forEach((route) => {
        const tmp = { ...route };
        if (hasPermission(roles, tmp)) {
            if (tmp.children) {
                tmp.children = filterAsyncRouter(tmp.children, roles);
} res.push(tmp); } });
return res; } const state = { routers: constantRouterMap, addRouters: [], }; const getters = { permission_routers: (state) => state.routers, addRouters: (state) => state.addRouters, }; const mutations = { SET_ROUTERS: (state, routers) => { state.addRouters = routers;
state.routers
= constantRouterMap.concat(routers); console.log(state.routers); }, }; const actions = { GenerateRoutes({ commit }, data) {
return new Promise((resolve) => { const { roles } = data; let accessedRouters; if (roles.includes("admin")) { accessedRouters = asyncRouterMap; } else { accessedRouters = filterAsyncRouter(asyncRouterMap, roles); } commit("SET_ROUTERS", accessedRouters); resolve(); }); }, }; export default { namespaced: true,//vuex 命名空间 state, getters, mutations, actions, };

 

Guess you like

Origin www.cnblogs.com/wangchao1990/p/12756216.html