您的位置:首页 > Web前端 > Vue.js

vue路由守卫+登录态管理

2018-10-30 16:45 489 查看

在路由文件需要守卫的path后面加上meta

{path: '/home',component: home,meta:{requireAuth:true}}

在main.js里面加上

//路由守卫
router.beforeEach((to, from, next) => {
console.log(to);
console.log(from);
if (to.meta.requireAuth) { // 判断该路由是否需要登录权限
if(JSON.parse(localStorage.getItem('islogin'))){ //判断本地是否存在access_token
next();
}else {
next({
path:'/login'
})
}
}
else {
next();
}
/*如果本地 存在 token 则 不允许直接跳转到 登录页面*/
if(to.fullPath == "/login"){
if(JSON.parse(localStorage.getItem('islogin'))){
next({
path:from.fullPath
});
}else {
next();
}
}
});

其中islogin是登录态,就是true or false,true表示登录,false表示未登录,存放在localStorage里面,因为localStorage里面只能存字符串,所以存进去的时候需要localStorage.setItem(‘islogin’,JSON.stringify(islogin));将islogin变为String类型,取出来的时候需要将islogin转化为Boolean类型,就比如JSON.parse(localStorage.getItem(‘islogin’))这样。
那么还有一个问题,就是islogin登录态的管理,vue不能实时监测localStorage的变化,需要实时监测islogin的变化来在页面显示登录还是已经登录,我用的是vuex+localStorage来管理islogin。展示部分代码

//store.js中
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
state:{
//是否登录判断
islogin:''
},
mutations:{
login:(state,n) => {
//传入登录状态islogin
let islogin = JSON.parse(n);
localStorage.setItem('islogin',JSON.stringify(islogin));
console.log(islogin);
state.islogin = islogin;
}
}
}

在需要改变登录态的页面只要触发上面这个login方法就可以了

//这里是登录
login() {
let flag = true;
this.$store.commit('login',flag);
this.$router.push("/home");
console.log("登录成功");
}
//这里是退出登录
exit() {
let flag = false;
this.$store.commit('login',flag);
this.$router.push("/login");
console.log("退出登录");
}

登录注册部分样式参考的element-ui
http://note.youdao.com/noteshare?id=f670900256dc51a19c36f31a5933febf

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: