在路由的配置文件里
const router = new VueRouter({ ... })
router.beforeEach((to, from, next) => {
// ...
})
-------------------------------demo01--------------------------------------
router.beforeEach((to, from, next) => {
if (to.matched.some(res => res.meta.requireAuth)) {// 判断是否需要登录权限
if (axiosCookie.getCookie("user_id")) {// 判断是否登录
next()
} else {// 没登录则跳转到登录界面
next({
path: '/user/login',
query: {redirect: to.fullPath}
})
}
} else {
next()
}
})
------------------------demo02---------------------------------------------
//路由跳转前验证登录
vueRouter.beforeEach(function(to,from,next){
// console.log(to);
// console.log(from);
// console.log(next);
// let login = localStorage.getItem('token'); //判断登录状态的; 也可以从 store 里拿到这个状态const auth = store.state.auth.IsLogin;
let login = true; //临时赋值 让函数能执行
let path = to.path
if (path === '/user/login') {
next()
return
}
if (login) {
if (path === '/') { //默认跳到首页
console.log('走了这里');
next({
path: '/Home'
})
} else {
console.log('走了默认');
next(); //进行管道中的下一个钩子
}
}else {
next({
path: '/user/login' //跳转到一个不同的地址
})
}
});
---------------------------------------------------------------------
写在main.js里axios的config配置里
const userId = axiosCookie.getCookie("user_id");
if (userId) {
//config.headers.cookie = 'user_id='+userId+';secure';
document.cookie = 'user_id='+userId+';secure';
}
getCookie见阿里云文件库
相关文献:
https://blog.csdn.net/latency_cheng/article/details/78580161 方法解释
https://www.cnblogs.com/wuvkcyan/p/9311155.html 方法解释
https://segmentfault.com/q/1010000015834262