在開發管理端項目,常常需要根據當前登錄者獲取對應的權限和對應的菜單,展示不同的頁面。而如果不做全局路由守衛的話,手動改變url為項目中真實存在的路由地址時,頁面會正常跳轉,但是其實不應該讓用戶看到該頁面。
代碼邏輯如下:
所有用戶都可以訪問白名單中的路由和自己能看到的menuList中的菜單
但是如果用戶在url中直接修改,應該根據權限判斷是否能看到
沒有權限則跳轉到noPerm頁面,此處需要注意如果瀏覽器的URL改變了 (可能是用戶手動或者瀏覽器后退按鈕),那么 URL 地址會重置到 from 路由對應的地址
next(false): 中斷當前的導航(參見vue router全局前置守衛文檔)
1 export default ({ app }) => { 2 app.router.beforeEach((to, from, next) => { 3 const menuList = sessionStorage.getItem('mainMenu'); 4 const whiteList = ['/login', '/noPerm', '/']; 5 if (whiteList.includes(to.path)) { 6 // 用戶手動或者瀏覽器后退按鈕改變url 7 if (from.path === '/') { 8 // 中斷當前的導航 否則跳轉到/路徑下,展示頁面不存在 9 next(false); 10 } 11 next(); 12 } else if (menuList) { 13 const menuPathList = JSON.parse(menuList).map((item) => item.path) || []; 14 if (menuPathList.includes(to.path)) { 15 next(); 16 } else { 17 next({ path: '/noPerm', replace: true }); 18 } 19 } else { 20 next({ path: '/login' }); 21 } 22 }); 23 };