8-1 路由导航守卫知识梳理
1.获取地址栏里面的参数 可以携带token,query parmas,
1.通过location和sessionStoreage 命名并保存到本地缓存
session可以通过手动释放,通常关闭一个页面就会结束当前的session会话,
window.location.search.split(1)[0];
2.router.beforeEach(to,form,next)
通过全局的router.js文件获取到路由,并通过配置参数对路由权限进行管理和分配
通常对token进行判断
代码:
1.无登录接口
router. beforeEach((to, from, next) => {
// var token = window.localStorage.getItem(“token”); // 存储token
const role = “admin”;
console.log(window.location.search);
document.title = getPageTitle(to.meta.title); // 路由中设置页面标题
if (window.location.search !== “” || to.meta.nacy == “true”) {
// to.meta.nacy=='true’这里面的nacy就是自己在路由中设置的//不参与token验证的页面参数变量这个变量可以自己定义
next();
const accessRoutes = store.dispatch(“permission/generateRoutes”, role);
router.addRoutes(accessRoutes);
} else {
if (to.path == “/login”) {
next();
} else {
next(“/login”);
}
}
});
2.有登录接口:
// router.beforeEach(async (to, from, next) => {
// // start progress bar
// NProgress.start();
// // set page title
// document.title = getPageTitle(to.meta.title);
// // determine whether the user has logged in
// // const hasToken = getToken()
// // if (hasToken) {
// // if (to.path === ‘/login’) {
// // // if is logged in, redirect to the home page
// // next({ path: ‘/’ })
// // NProgress.done()
// // } else {
// // // determine whether the user has obtained his permission roles through getInfo
// // const hasRoles = store.getters.roles && store.getters.roles.length > 0
// // if (hasRoles) {
// // next()
// // } else {
// // try {
// // // get user info
// // // note: roles must be a object array! such as: [‘admin’] or ,[‘developer’,‘editor’]
// // const { roles } = await store.dispatch(‘user/getInfo’)
// // // generate accessible routes map based on roles
// // const accessRoutes = await store.dispatch(‘permission/generateRoutes’, roles)
// // // dynamically add accessible routes
// // router.addRoutes(accessRoutes)
// // // hack method to ensure that addRoutes is complete
// // // set the replace: true, so the navigation will not leave a history record
// // next({ …to, replace: true })
// // } catch (error) {
// // // remove token and go to login page to re-login
// // await store.dispatch(‘user/resetToken’)
// // Message.error(error || ‘Has Error’)
// // next(/login?redirect=${to.path}
)
// // NProgress.done()
// // }
// // }
// // }
// // } else {
// // /* has no token*/
// // if (whiteList.indexOf(to.path) !== -1) {
// // // in the free login whitelist, go directly
// // next()
// // } else {
// // // other pages that do not have permission to access are redirected to the login page.
// // next(/login?redirect=${to.path}
)
// // NProgress.done()
// // }
// // }
也可以通过 window.open(“url”, “_parent”, “”);
返回到头部的地址栏中
next(/login?redirect=${to.fullPath}
);