DEV Community

Maji-May
Maji-May

Posted on • Updated on

Practical use of Vue-router navigation guard

Suppose that there are two types of roles, "admin" and "user". Users are allowed to visit the equipment page. Admins can manage users and can also enter the equipment page by changing the URL.

In /router/index.js

import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

// 公共路由
export const constantRoutes = [{
        path: '/login',
        component: () => import("@/view/login/index.vue"),
    },
    {
        path: '/',
        component: () => import("@/view/layout/index.vue"),
        meta: {
            require: true,
        },
        redirect: '/user',
        children: [{
                path: '/user',
                component: () => import("@/view/user/index.vue"),
                meta: {
                    title: 'User Management', 
                    require: true,
                    keepAlive: true,
                    role: 0
                }
            },
            {
                path: '/chagePwd',
                component: () => import("@/view/changePwd/index.vue"),
                meta: {
                    title: 'Change Password',
                    require: true,
                    keepAlive: true,
                    role: 1
                }
            },
            {
                path: '/userDetail',
                component: () => import("@/view/user/userDetail.vue"),
                meta: {
                    title: 'User Detail',
                    require: true,
                    keepAlive: false,
                    role: 0
                }
            },
            {
                path: '/equipment',
                component: () => import("@/view/equipment/index.vue"),
                meta: {
                    title: 'Equipment Resource Management',
                    require: true,
                    keepAlive: true,
                    role: 1
                }
            },
            {
                path: '/equipmentDetail',
                component: () => import("@/view/equipment/equipmentDetail.vue"),
                meta: {
                    title: 'Equipment Resource Detail',
                    require: true,
                    keepAlive: false,
                    role: 1
                }
            },
        ]
    },
    {
        path: '*',
        component: () => import("@/view/err/404.vue"),
        meta: {
            title: '404'
        }
    }
]
//动态路由添加 Add Dynamic Routers 
export const DynamicRouting = {}
const router = new Router({
    mode: 'hash',
    scrollBehavior: () => ({
        y: 0
    }),
    routes: constantRoutes
})


const originalPush = Router.prototype.push
Router.prototype.push = function push(location) {
    return originalPush.call(this, location).catch(err => err)
}

export default router
Enter fullscreen mode Exit fullscreen mode

/router/permissions.js

import router from "./index"
import {
    getToken
} from '@/utils/auth'
import Vue from "vue"
router.beforeEach((to, from, next) => {
    const token = getToken()
    if (token) {
        //有token (token avaliable)
        let role = localStorage.getItem('role')
        if (role == '1' && to.path == '/user') {
            //用户不允许管理用户 (users are not allowed to manage themselves)
            next('/equipment')
        } else {
            //管理员正常放行 (admins can pass freely)
            next()
        }
    } else {

        //无token,登录页面直接next (token unavaliable, jump into login page)
        if (to.path === '/login') {
            next()
        } else {
            next('/login')
        }

    }
})


router.afterEach((to, from) => {
    console.log('afterEach', to, from)
    if (to.meta.title) {
        document.title = to.meta.title //修改网页的title (change the title of this website)
    } else {
        document.title = localStorage.headerTxt || Vue.prototype.$vue_config.headerTxt
    }
})
Enter fullscreen mode Exit fullscreen mode

main.js

...
import "./router/permission"
...
Enter fullscreen mode Exit fullscreen mode

A simple flow chart.

image-20220526191610076)

Top comments (0)