刷新页面后,vuex中数据丢失,清空的解决方案vuex-persistedstate

在nuxt中使用vuex-persistedstate(场景是登录后存储用户的信息)

1.login.vue

async login(params) {
      try {
        const res = await login(Object.assign(params, this.getcodeinfo));
        if (res.code == 200) {
          this.$message.success("登录成功!");
          this.form.resetFields();
          this.SAVEUSERINFO(res.data);//保存用户信息
          this.$router.push("/");
        } else {
          this.$message.error(res.info);
        }
      } catch (error) {
        console.error(error);
      }
},

2.mutation.js

export default {
  SAVEUSERINFO(state, info){
    state.user = info
  },
  REMOVEUSERINFO(state){
    state.user = {}
  }
}

3.default.vue

<a-menu-item class="header-right" v-if="getToken !== ''">
          <a-tooltip overlayClassName="tooltip">
            <template slot="title">
              <section class="tooltip-cont">
                <h2>{{getName}}</h2>
                <p>个人中心</p>
                <p @click="logout">退出</p>
              </section>
            </template>
            <a-avatar icon="user" />
          </a-tooltip>
        </a-menu-item>
</a-menu>



computed: {
    ...mapGetters([
      "getToken",
      "getName"
    ])
},


methods:
...mapMutations(["REMOVEUSERINFO"]),

async logout() {
      try {
        const res = await logout({ token: this.getToken });
        if (res.code == 200) {
          this.$message.success("注销成功!");
          this.REMOVEUSERINFO();//清除用户信息
          this.$router.go(0);
        } else {
          this.$message.error(res.info);
        }
      } catch (error) {
        console.error(error);
      }
}

4.getters.js

export default {
  getToken (state) {
    return state.user && state.user.token
  },
  getName (state) {
    return state.user && state.user.username
  }
}

5.持久化处理

先安装  : npm i vuex-persistedstate --save

plugins文件下新建localStorage.js

import createPersistedState from "vuex-persistedstate"

export default ({store}) => {
  createPersistedState({
  })(store)
}

具体vuex-persistedstate操作请看:https://github.com/robinvdvleuten/vuex-persistedstate

参考:https://segmentfault.com/a/1190000019077724

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值