如何确保 Vue 在登录成功后立即获取到 localStorage 中的值?

作者站长头像
站长
· 阅读数 22

由于登录成功后马上跳转回主页,导致存localStorage操作与路由跳转几乎同时进行,所以跳转回主页后,localStorage还没有存入完成,获取不到用户信息,只有在刷新一下才能获取到值,如何在登陆成功后获取到呢?

user.js里面将用户信息存储到localStorage中:

const actions = {
  getUserInfo({
    commit,
    dispatch,
    state
  }) {
    axios({
      method: 'get',
      url: '/gateway/api/userInfo',
      headers: {
        'admin-gateway-token': state.token
      }
    }).then(res => {
      const {
        data,
        code,
        msg
      } = res.data
      if (code === 0) {
        localStorage.setItem('userInfo', data.username)
        commit('SET_USERINFO', data)
      } else {
        console.log('获取人员信息失败:', res)
        if (res.data.code === 2000) {
          dispatch('app/logOut', {}, {
            root: true
          })
        }
        Message({
          type: 'error',
          message: '获取人员信息失败:' + msg
        })
      }
    }, res => {
      Message({
        type: 'error',
        message: '获取人员信息失败:' + res
      })
    })
  },
回复
1个回答
avatar
test
2024-06-21

你都用 store 了,设置 localStorage 的时候同时也操作修改一下 state 的值不行么……为啥一定要用 ls 绕一下。

回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容