vue用户登录状态判断

之前项目中用来判断是否登录我写了多种方案,但是最终只有一个方案是比较好的,这篇博客就是分享该方案;

先说基本要求:

  • 项目中的登录状态是依据服务器里的状态来作为判断依据;
  • 每一个需要登录后才能操作的接口,如果未登录都会返回未登录的错误;
  • 项目中使用 vuex,axios,router;

判断登录方案需要满足下面几点:

  1. 未登录状态下的刷新:
    1.1 在需要登录页面中刷新是需要跳转到登录页的;
    1.2 在不需要登录的页面中刷新,不需要跳转;
  2. 在未登录状态下,跳转到需要登录页面时,会直接跳转到登录页;

先在路由文件里修改:

export default {
  path: '/person',
  component: person,
  name: 'person',
  redirect: 'person/index',
  meta:{
    requireLogin:true,
  },
  children: [
      //子页面
    ]
  }

假如上面的代码是一个用户中心的路由,他是主页面,其他都是他的子页面,那么只需要在meta里添加requireLogin:true一次就行了,子页面不需要修改什么;


在 main.js 里添加:

axios.interceptors.response.use(
    response => {
	  if(response.data.code === 500) {
        if (response.data.msg === '请先登录') {
          router.push({
            path: '/login',
            query: {redirect: router.history.current.fullPath}
          })
          //如果需要可以在这里将 vuex 里的 user 改为空对象
        }
      //显示错误信息
      return Promise.reject(response.data)
    }

    if(response.data.code === 0){
      return response;
    }
}, error => {
    //显示错误信息
    return Promise.reject(error.response.data)
});


router.beforeEach((to, from, next) => {
  let user = router.app.$options.store.state.user;
  if (to.matched.some(record => record.meta.requireLogin)) {
    if (JSON.stringify(user) === '{}') {
      next();
      router.push({ path: '/login',query: { redirect: to.fullPath }})
    }else {
      next()
    }
  } else {
    next()
  }
});

根据 user 是否为一个空对象来判断本地登录状态;


在 app.vue 里添加:

created(){
    this.$store.dispatch('getUser');
}

每一次刷新都会触发该函数,作用是判断登录状态和获取最新的信息;


在 vuex/index 添加:

const store = new Vuex.Store({
    state: {
        user: JSON.parse(localStorage.user || '{}'),
    },
    mutations: {
        changeUser(state, msg){
            state.user = msg;
        },
    },
    actions: {
        getUser({commit}){
          axios.get(api.info).then(data => {
            commit('changeUser', data.data.member);//需根据实际修改
            localStorage.user = JSON.stringify(data.data.member || {});
          }).catch(err => {
            commit('changeUser', {});
            if (router.currentRoute.matched.some(record => record.meta.requireLogin)) {
              router.push({
                path: '/login',
                query: {redirect: router.currentRoute.fullPath}
              })
            }
          })
        },
    }
})

在某页面下刷新,可以根据是否为需登录页面进行判断,并且已登录可以更新用户信息;
用户的信息都是存储在 localStorage 里来成为默认值,但是 ajax 连接失败的话,会变为空;

!!注意!!
上面的方法适用的是,不知道后台的登录保存时间,然而,如果你知道后台的登录状态保存时间的话,我想可以有一种更好的方法,即 cookie
因为 cookie 会有一个保存的时间, 进入一个页面判断是否存在;
还可以使用 Web Workers ,在后台添加一个计时器,每一段时间判断 cookie 是否存在,不过 cookie 能存储的东西不多,还有 IE 对Web Workers 是不支持的,所以最好在 main 里判断一下页面是否对 web workers ;

放下我之前项目所用的登录检查方式:

let hasLogin = false // 是否登录过
// 登录拦截
router.beforeEach((to, from, next) => {
    if (document.cookie.includes('userName')) {
        hasLogin = true
        if (permission.indexOf(to.path) > -1) {
            next()
        } else {
            try {
                // 简单的权限判断
                let routesKey = Cookie.get('routesKey').split(',')
                let key = to.path.split('/')[1]
                if (routesKey.indexOf(key) > -1) {
                    next()
                } else {
                    next({path: '/'})
                }
            } catch (e) {
                next({path: '/login'})
            }
        }
    } else {
        if (to.path === '/login') { // 如果是登录页面路径,就直接next()
            next()
        } else {
            if (hasLogin) {
                Cookie.clear('userName')
                ELEMENT.Message({
                    message: '登录失效,请重新登录!',
                    center: true,
                    type: 'warning'
                })
            }
            next({path: '/login', query: {redirect: to.fullPath}})
        }
    }
})

完;

posted @ 2018-02-11 10:55  Grewer  阅读(25023)  评论(0编辑  收藏  举报