第一步:注冊頁面所有的路由,此處代碼省略,注意404路由一定要放在最下面
1 ... 2 { 3 path: '/404', 4 name: '404', 5 component: notFound, 6 hidden: true 7 }, 8 { 9 path: '*', 10 redirect: '/404', 11 hidden: true 12 }
第二步:創建router 對路由進行管理
const router = new Router({ mode: 'hash', //相對於hash模式,url顯示更友好 routes, //routes相當於routes:routes strict: process.env.NODE_ENV !== 'production' //非生產模式下采用嚴格模式 });
第三步也是最關鍵的一步,權限驗證也在這里做
1 router.beforeEach((to, from, next) => { 2 if (!getStoreJson("CurUser") && to.path !== '/') { 3 // 如果沒有登錄 先登錄 4 next({ 5 path: '/' 6 }); 7 } else { 8 if (to.path === '/' || to.path == '/404' || to.path == '/500') { 9 // 不加會死循環 10 next(); 11 } else { 12 //判斷訪問的頁面是否授權 13 var isAuth = isAuthorized(to.path); 14 if (!isAuth) { 15 //如果沒有授權,自動跳轉到404頁面 16 next({ 17 path: '/404' 18 }); 19 } else { 20 //如果授權,繼續下一步 21 next(); 22 } 23 } 24 } 25 });
這樣就完成了