programing

vuex-persisted state를 사용한 영구 상태: 다른 탭의 상태를 변환해도 첫 번째 탭의 저장 상태가 업데이트되지 않음

bestcode 2022. 8. 11. 23:03
반응형

vuex-persisted state를 사용한 영구 상태: 다른 탭의 상태를 변환해도 첫 번째 탭의 저장 상태가 업데이트되지 않음

안녕하세요. vuex persisted state를 사용하여 상태를 유지하고 있습니다.

import createPersistedState from 'vuex-persistedstate'

const store = new Vuex.Store({
// ...
    plugins: [createPersistedState()]
})

다른 탭에서 스토어 상태를 업데이트하고 업데이트된 스토어 상태를 앱의 다른 열린 탭에 반영하고 싶습니다.

어떻게 하면 그렇게 할 수 있을까?

vuex-shared-mutations 를 사용합니다.

GitHub 링크

여기에 이미지 설명 입력

를 실장해 볼 수 있습니다.window.onfocus이벤트를 통해 새 탭으로 이동하면getState메서드가 호출됩니다.

를 들을 수 있습니다.storage이벤트. https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API에서 스토리지 이벤트를 통한 스토리지 변경에 대한 응답을 참조하십시오.

window.addEventListener("storage", e => {
    // ...
});

예: https://github.com/jacobgoh101/vuex-sync-tabs-example

인스톨 되어 있습니다.

import Vue from "vue";
import Vuex from "vuex";
import createPersistedState from "vuex-persistedstate";

Vue.use(Vuex);

export default new Vuex.Store({
  plugins: [createPersistedState()],
  state: {
    count: 2
  },
  mutations: {
    increment(state) {
      state.count++;
    },
    setAll(state, payload) {
      state.count = payload.count;
    }
  },
  actions: {}
});

App.vue에서

<template>
  <div id="app">
    store count: {{$store.state.count}}
    <br>
    <button @click="$store.commit('increment')">add</button>
  </div>
</template>

<script>
export default {
  name: "app",
  mounted() {
    window.addEventListener("storage", e => {
      if (e.key !== "vuex") return;

      // exit if no change
      if (e.newValue === JSON.stringify(this.$store.state)) return;

      const persistedData = JSON.parse(e.newValue);

      this.$store.commit("setAll", persistedData);
    });
  }
};
</script>

언급URL : https://stackoverflow.com/questions/49839307/persistent-state-using-vuex-persistedstate-store-state-in-first-tab-doesnot-upd

반응형