1、比如我是寫在根目錄的:
2、點擊跳轉到沒權限的路由(因為沒權限,該路由找不到,顯示空白頁):
3、路由守衛如下:
router.beforeEach((to, from, next) => { const hasToken = getToken(); // console.log(hasToken) // console.log('length=' + getRouter.length) if(!getObjArr('router')) { getRouter = [] // console.log(getRouter) } // console.log(getRouter); // 后端路由 if (getRouter.length === 0) { // 不加這個判斷,路由會陷入死循環 if (!getObjArr('router')) { if (to.path === '/login' || from.path === '/dashboard' || from.path === '/') { // 若用戶已經登錄,則重定向到主頁 // || from.fullPath === '/' || from.fullPath === '/dashboard' } else {
//獲取路由接口 getMenu().then(res => { var conet = [] var head = [] res.menu.forEach((items, index) => { items.meta = { title: items.name, icon: 'dashboard' // items.icon } if (items.parentId) { conet.push(items) } else { items.children = [] head.push(items) } }) head.forEach((items, index) => { conet.forEach((item, index) => { if (items.id === item.parentId) { items.children.push(item) } }) }) getRouter = head saveObjArr('router', getRouter) routerGo(to, next) // location.reload() }).catch(() => { }) } } else { // 從localStorage拿到了路由 getRouter = getObjArr('router') // 拿到路由 routerGo(to, next) } } else { next() }
4、此時無權限路由跳轉為空白頁,需要添加如下(此時未匹配到的路由,會跳轉到404頁面):
} else if(to.matched.length === 0) {
from.path? next({ path: '*', redirect: '/404', hidden: true }) : next('/'); //404頁面內容可以自定義
} else {
next()
}
注:每個人的路由守衛頁面、路由寫法等都不一樣,所以該博客僅供參考!