解决vue开发的项目中,登录过后,使用cookie 保持登录状态
关于vue登录注册,并保持登录状态,是vue开发者必须要走的路,网上也有很多的解决方法说的模棱两可,让人无处下手,下面我就根据项目的经验给出解决方案。
项目中有一些路由是需要登录才可以进入的,比如列表详情,个人中心等等
有一些路由是不需要登录就可以进入,比如首页,列表页等等
那如何判断路由是否需要登录呢?就要在路由routes.js里面做文章
举个栗子,以下是routes.js 中部分代码
1 { 2 //登录 3 path: ‘/login‘, 4 component: Login, 5 meta: { 6 requireLogin: false 7 } 8 }, 9 { 10 //我的学习 11 path: ‘/mobileStudy‘, 12 component: MobileStudy, 13 meta: { 14 requireLogin: true 15 } 16 },
接下来我们在login.vue中修改登录后状态,并且存放cookie(别忘了给cookie 设置有效时间,否则cookie 就是临时性的)
我们使用axios向后台发起登录请求,我们项目是经过封装过后的 axios
1 setUserInfo: function (md5Password) { 2 if (this.remember) { 3 this.setCookie("mobile", this.mobile,有效期); 4 this.setCookie("password", md5Password,有效期); 5 } else { 6 this.setCookie("mobile", ""); 7 this.setCookie("password", ""); 8 }
1 this.$axiosPackag.getMessageByAxios( 2 "POST", 3 "登录接口", 4 {需要传给后台的参数) }, 5 null, 6 null, 7 resD => { 8 if (resD) { 9 this.setUserInfo(md5(this.password)); 10 this.$toast("登录成功"); 11 12 }); 13 14 } 15 }, 16 errorCall => { 17 } 18 );
重点来了~,在main.js里
1 /** 2 * 路由的拦截 3 */ 4 router.beforeEach((to, from, next) => { 5 if (to.meta.requireLogin) { 6 if (Cookies.get(‘mobile‘) && Cookies.get(‘password‘)) { // 判断浏览器cookie中 是否还有 mobile 和 密码,即使关闭浏览器,也不用重新登录了 7 next( 8 $.ajax({ 9 url: process.env.API_URL+‘接口‘, 10 type: ‘POST‘, 11 async: false, 12 data: { userName: Cookies.get(‘mobile‘), password1: Cookies.get(‘password‘) }, 13 timeout: 5000, 14 dataType: ‘json‘, 15 success: function (data) { 16 17 }, 18 error: function (xhr, textStatus) { 19 console.log(‘路由认证失败了!!‘ + textStatus); 20 } 21 }) 22 ); 23 } else { 24 next({path: "login", query: {redirect:to.fullPath}}); 25 } 26 27 } else { 28 next(); 29 } 30 });
如果有帮到你的话,请给点个赞吧!
文章来自:https://www.cnblogs.com/xyhailong/p/12462898.html