source

Vuex-persist가 localStorage에 아무것도 저장하지 않는 이유는 무엇입니까?

goodcode 2022. 8. 25. 23:53
반응형

Vuex-persist가 localStorage에 아무것도 저장하지 않는 이유는 무엇입니까?

따라서 프로젝트(Vue-cli + TypeScript)에서는 사용자 데이터를 locaStorage에 저장해야 합니다.이를 위해 vuex와 함께 vuex-persist(npm 플러그인)를 사용하기로 결정했습니다.그러나 DevTool에서는 localStorage에 아무것도 표시되지 않습니다.내 코드에 뭐가 잘못됐지?잘 부탁드립니다.

이전 프로젝트에서 이미 이 도구 조합을 사용했는데 잘 작동합니다.이 프로젝트에서는 같은 설정을 사용하지만 동작하지 않습니다.이것은 가장 이상한 점입니다.

Structure Module.ts 입니다.

import { ActionTree, MutationTree, GetterTree, Module } from "vuex";

const namespaced: boolean = true;

interface IDataStructure {
    name: string;
    type: string;
    description: string;
}

interface IStructureState {
    name: string;
    description: string;
    props: IDataStructure[];
}


export interface IState {
    structures: IStructureState[];
}

export const state: IState = {
    structures: [
        {
            name: "",
            description: "",
            props: [
                {
                    name: "",
                    type: "",
                    description: "",
                },
            ],
        },
    ],
};

export const actions: ActionTree<IState, any> = {
    addNewDataStructure({ commit }, payload: IStructureState): void {
        commit("ADD_DATA_STRUCTURE", payload);
    },
    updateDataStructure({ commit }, payload: IStructureState): void {
        commit("UPDATE_EXISTING_DATA_STRUCTURE", payload);
    },
    clearDataStructure({ commit }, { name }: IStructureState): void {
        commit(" CLEAR_DATA_STRUCTURE", name);
    },
};

export const mutations: MutationTree<IState> = {
    ADD_DATA_STRUCTURE(state: IState, payload: IStructureState) {
        if (state.structures[0].name === "") {
            state.structures.splice(0, 1);
        }
        state.structures.push(payload);
    },

    CLEAR_DATA_STRUCTURE(state: IState, name: string) {
        state.structures.filter((structure: IStructureState) => {
            if (structure.name === name) {
                state.structures.splice( state.structures.indexOf(structure), 1);
            }
        });
    },

    UPDATE_EXISTING_DATA_STRUCTURE(state: IState, payload: IStructureState) {
        state.structures.map((structure: IStructureState) => {
            if (structure.name === payload.name) {
                state.structures[state.structures.indexOf(structure)] = payload;
            }
        });
    },
};

export const getters: GetterTree<IState, any> = {
    dataStructureByName(state: IState, structName: string): IStructureState[] {
        const structure: IStructureState[] = state.structures.filter((struct: IStructureState) => {
            if (struct.name === structName) {
                return struct;
            }
        });
        return structure;
    },

    dataStructures(): IStructureState[] {
        return state.structures;
    },
};

export const StructureModule: Module<IState, any> = {
    namespaced,
    state,
    mutations,
    actions,
    getters,
};

index.ts 입니다.

import Vue from "vue";
import Vuex, { ModuleTree } from "vuex";
import VuexPersistence from "vuex-persist";

import { StructureModule , IState} from "./modules/StructureModule";

Vue.use(Vuex);

const storeModules: ModuleTree<IState> = {
    StructureModule,
};

const vuexPersistentSessionStorage = new VuexPersistence({
    key: "test",
    modules: ["StructureModule"],
});


export default new Vuex.Store<any>({
    modules: storeModules,
    plugins: [vuexPersistentSessionStorage.plugin],
});

이것은 main.ts 입니다.


import store from "@/store/index.ts";
import * as $ from "jquery";
import Vue from "vue";

import App from "./App.vue";
import router from "./router";

global.EventBus = new Vue();
(global as any).$ = $;
Vue.config.productionTip = false;
console.log(store);
new Vue({
  router,
  store,
  render: (h) => h(App),
}).$mount("#app");

vue.config.js 입니다.

module.exports = {
    transpileDependencies: ["vuex-persist"],
};

이것은 vue-devtool에 저장되어 있습니다. 이것은 dev-tool local Storage 입니다.

로컬 스토리지에는 미리 정의된 값을 가진 키 "test"가 있는 스토리지가 나타나지만 이 localStorage가 비어 있습니다.

가이드에 기재된 바와 같이

Vuex 스토어에서 실제로 상태를 변경하는 유일한 방법은 변환을 커밋하는 것입니다.

https://vuex.vuejs.org/guide/mutations.html

당신 코드에는 변이가 없는 것 같아요.

그렇지 않으면 https://github.com/robinvdvleuten/vuex-persistedstate,을 봐주세요.인기 있는 것 같고, 저는 문제없이 사용하고 있습니다.

사용법은 매우 간단합니다.스토어 내에서 플러그인을 선언하기만 하면 됩니다.

import createPersistedState from 'vuex-persistedstate'

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

나는 이 문제에 대한 해결책을 찾았다.내 경우엔 이름 앞부분만 지우고

export const StructureModule: Module<IState, any> = {
    namespaced, <----- This
    state,
    mutations,
    actions,
    getters,
};

namesched는 여러 모듈이 있는 경우에만 사용해야 합니다.

언급URL : https://stackoverflow.com/questions/56685536/why-vuex-persist-doesnt-store-anything-in-localstorage

반응형