Practical use of Vue-router navigation guard
Tags: vue, webdev
Published: 2022-06-19 10:34:47

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`

```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
```

`/router/permissions.js`

```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
	}
})
```

`main.js`

```js
...
import "./router/permission"
...
```

A simple flow chart.

![image-20220526191610076](https://image-1256777099.cos.ap-beijing-fsi.myqcloud.com/blog2022image-20220526191610076.png))