第一步:注册页面所有的路由,此处代码省略,注意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 });
这样就完成了