programing

VueX에서 지속적인 상태 잠금 방지

randomtip 2022. 7. 21. 21:56
반응형

VueX에서 지속적인 상태 잠금 방지

를 사용하고 있습니다.vuex-persistedstate내 상태를 추적하고 지속시키는 모듈localStorage문제는 저장해야 할 상태의 양 때문에 데이터가 갱신될 때마다 앱이 잠긴다는 것입니다.

이를 해결하기 위해 문자열 생성 중에 비즈니스 계산을 할 수 있는 약속을 사용하려고 합니다.문자열이 준비되면 다음으로 설정합니다.localStorage.

여기 있습니다.

const buildLocalStorageString = async (state) => {
  return await JSON.stringify(state);
}

export default new Vuex.Store({
  state: { etc, etc, etc },

  plugins: [createPersistedState({
    key: 'myApp',
    setState (key, state, storage) {
      buildLocalStorageString(state).then(string => {
        storage.setItem(key, string) 
      }) 
    }
  })],
})

문제는 그것이 문제를 해결하지 못한다는 것이다.앱 업데이트 시 아직 상당한 지연이 있습니다.

모든 localStorage 호출이 동기화됩니다.Javascript는 단일 스레드입니다.1개의 큰 데이터 청크를 로컬 스토리지에 저장하면 항상 다른 모든 실행이 차단됩니다.

데이터를 분할하여 로컬 스토리지에 저장함으로써 해결할 수 있습니다.기본적으로는 여러 개를 사용합니다.createPersistedState.

극히 간단한 구현 예는 다음과 같습니다.

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

Vue.use(Vuex)

const moduleA = {
    state: {
        a: 'a'
    },
    mutations: {
        updateA(state) {
            state.a += 'a';
        }
    }
}

const moduleB = {
    state: {
        b: 'b'
    }
}

export default new Vuex.Store({
    modules: {
        moduleA: moduleA,
        moduleB: moduleB
    },
    plugins: [createPersistedState({
        key: 'vuex_a',
        paths: ['moduleA']
    }), createPersistedState({
        key: 'vuex_b',
        paths: ['moduleB']
    })]
})

언급URL : https://stackoverflow.com/questions/51784569/prevent-persisted-state-locking-up-app-in-vuex

반응형