Vue 中首次登录 store 无法获取用户信息的解决方案是什么?

vue 中首次登录 store 无法获取用户信息的解决方案是什么?

vue 中首次登录时 store 无法获取的问题解决方案

在 vue 中,首次登录进入页面时无法从 store 中获取值的常见原因是使用了 mapstate 但没有正确获取整个 state 对象。在给出的问题中,代码中使用了 mapstate({ userinfo: (state) => state.user.userinfo }) 来映射 store 中的 userinfo 值,但这种写法仅获取了 userinfo 的子对象,而不是完整的 state 对象。

在方法中,调用 this.userinfo.username 时会返回 undefined,因为 this.userinfo 本身就是 undefined。因此,需要修改 mapstate 以获取整个 state 对象,如下所示:

computed: {  ...mapstate([    'user', // 获取完整的 user state  ]),},

登录后复制

然后,在方法中可以这样访问 username 值:

立即学习“前端免费学习笔记(深入)”;

async gettoptendata(params) {  let data;  this.searchloading = true  try {      data = await getcommtime({          account: this.user.userinfo.username,          dimension: this.activetoggle,          params      })  } catch (error) {      throw new error(error)  } finally {      this.searchloading = false  }  return { data: data.comm_task_list }},

登录后复制

此外,问题中提到了将 username 保存到 localstorage 的代码。该代码应该修改为:

if (code === 0) {  localStorage.setItem('userInfo', data) // 保存整个 data 对象  commit('SET_USERINFO', data)} else {  ...}

登录后复制

通过进行这些修改,userinfo 值应该可以在首次登录进入页面时从 store 和 localstorage 中正确获取。

以上就是Vue 中首次登录 store 无法获取用户信息的解决方案是什么?的详细内容,更多请关注【创想鸟】其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。

发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2662115.html

(0)
上一篇 2025年3月7日 11:09:23
下一篇 2025年2月23日 22:16:04

AD推荐 黄金广告位招租... 更多推荐

相关推荐

发表回复

登录后才能评论