刷新页面后,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


          
            
            
          
        




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

你可能感兴趣的:(vuex)