Ant Design Pro Vue 登录后userInfo存在vuex问题

问题描述:

作者发现使用Ant Design Pro中存在一个问题,页面刷新后vuex数据丢失,导致UserInfo找不到影响页面的问题,故而写此文,望能助有需之人。


原因分析:

提示:Vuex的机制问题

vuex是存在浏览器页面内存的数据,所以刷新后就没有了,虽然很多人认为存在localstorage或者sessionstorage内不安全,但作者还是习惯存在浏览器内存。


解决方案:

1.src/store/modules/user.js Login方法内存在LocalStorage中

2.src/permission.js 对应调整

作者的做法是让每一次原项目中的获取getInfo接口至vuex的机制,改为从localstorage中获取,是不是非常的机灵鬼呢 *~*

user.js

    // 登录
    Login ({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo).then(response => {
          const result = response.data
          storage.set(ACCESS_TOKEN, result.token, 7 * 24 * 60 * 60 * 1000)
          storage.set(REFRESH_TOKEN, result.refresh, 7 * 24 * 60 * 60 * 1000)
          storage.set(USER_INFO,result.userInfo,7 * 24 * 60 * 60 * 1000)
          commit('SET_INFO', result.userInfo)
          commit('SET_TOKEN', result.token)
          commit('SET_NAME', { name: result.userInfo.name, welcome: welcome() })
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

 permission.js


router.beforeEach((to, from, next) => {
  NProgress.start() // start progress bar
  to.meta && typeof to.meta.title !== 'undefined' && setDocumentTitle(`${i18nRender(to.meta.title)} - ${domTitle}`)
  /* has token */
  console.log(store);
  if (storage.get(ACCESS_TOKEN) && storage.get(USER_INFO)) {  //是否存在token和UserInfo
    // 每次变动都存储到vuex中
    store.commit('SET_INFO', storage.get(USER_INFO))
    store.commit('SET_TOKEN', storage.get(ACCESS_TOKEN))
    store.commit('SET_NAME', { name: storage.get(USER_INFO).name, welcome: welcome() })
    next()
  } else {
    if (allowList.includes(to.name)) {
      // 在免登录名单,直接进入
      next()
    } else {
      next({ path: loginRoutePath, query: { redirect: to.fullPath } })
      NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it
    }
  }
})

去尝试吧。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值