刷新頁面後,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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章