Vue-router 내비게이션 가드의 실용화
/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
/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
}
})
main.js
...
import "./router/permission"
...
간단한 흐름도.
)
Reference
이 문제에 관하여(Vue-router 내비게이션 가드의 실용화), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/flynncao/pratical-use-of-vue-router-navigation-guard-3d9i텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)