Programing

Vue CLI 쿠키 업데이트 또는 스토어 업데이트?

c10106 2022. 4. 22. 18:54
반응형

Vue CLI 쿠키 업데이트 또는 스토어 업데이트?

그래서 나는 Vue, Node와 프로젝트를 만들고 Vuex도 사용하고 있다.현재 나는 사용자 데이터를 vuex 매장이 아닌 쿠키에 저장하고 있다.그런데 실시간으로 사용자 데이터를 업데이트해야 하는 문제가 생겼어. 예를 들어 그가 물건을 살 때 웹페이지에 있는 돈을 업데이트해야 해.bow 내가 쿠키 값을 어떻게 바꾸니?쿠키를 업데이트 할 수 있는 방법이 있는지 아니면 vuex 스토어를 사용해야 하는지?

이를 위해 선호하는 방법은 상태를 vuex로 설정하고 내구성 플러그인을 사용하여 vuex 상태의 일부(또는 전체)를 유지하는 것이다.

예를 들어 vuex-perist를 사용할 수 있다.
에 대한 내장된 지원 기능localStorage,sessionStorage등등..
상태를 쿠키에 저장하려면 js-cookie를 사용하십시오.

import Vuex, { Store } from 'vuex';
import VuexPersistence from 'vuex-persist';
import Cookies from 'js-cookie';

const vuexCookie = new VuexPersistence({
  restoreState: (key, storage) => Cookies.getJSON(key),
  saveState: (key, state, storage) =>
    Cookies.set(key, state, {
      expires: 3
    }),
  modules: ['user'] // only save the user module state in the cookie
});

const store = new Store({
  modules: {
    user: {
      state: {name: "User 1"},
      // TODO: getters, mutations, etc...
    },
    // ... more modules
  },
  plugins: [vuexCookie.plugin]
});

(vuex-persist상세 예제에서 수정된 예)

모든 vuex 모듈에 대해 사용자 지정 내구성 전략을 지정할 수 있으므로 vuex 상태의 여러 부분에 대해 다른 내성 전략을 사용할 수 있다.

const vuexLocal = new VuexPersistence({
  storage: window.localStorage,
  reducer: (state) => ({ cache: state.cache }) //only save cache module
});
const vuexSession = new VuexPersistence({
  storage: window.sessionStorage,
  reducer: (state) => ({ user: state.user }) //only save user module
});

const store = new Vuex.Store({
  modules: {
    user: { /* ... */ }, // will be stored in sessionStorage
    cache: { /* ... */ }, // will be stored in localStorage
    foobar: { /* ... */ } // not persisted, will reset on page reload
  },
  plugins: [vuexLocal.plugin, vuexSession.plugin]
});

참조URL: https://stackoverflow.com/questions/57559287/vue-cli-updating-cookie-or-updating-store

반응형