Vue 使用beforeEach实现登录状态检查

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xukongjing1/article/details/82941159

使用VueRouter的beforeEach钩子函数,可以实现导航跳转前检查登录状态的需求。

1.在登录请求接口时返回用户的信息,比如 userInfo:{userId:'123', userName:'小明'},登录成功之后将userInfo存入store中。

2.使用beforeEach实现登录状态检查

vueRouter.beforeEach((to, from, next) => {
    //store的getters中定义获取用户信息的函数  getUser
    //userId为空说明用户未登录
    let isLogin = store.getters.getUser.userId;
    if (!isLogin) {//未登录
        if (to.path !== '/login') {//跳转到登录页
            return next({path: '/login'});
        }else {
            next();
        }
    }else {//已登录
        if (to.path === '/login') {//跳转到首页
            return next({path: '/index'});
        }
        next();
    }
});

如果需要退出登录,只需要将保存在store中的用户信息置空即可。

猜你喜欢

转载自blog.csdn.net/xukongjing1/article/details/82941159
今日推荐