Nuxt store 새로고침시 초기화 문제.

Aiden·2021년 3월 10일
0
post-custom-banner

vuex-persistedstate

Example with Nuxt.js
It is possible to use vuex-persistedstate with Nuxt.js. It must be included as a NuxtJS plugin:

With local storage (client-side only)
// nuxt.config.js

...
/*
 * Naming your plugin 'xxx.client.js' will make it execute only on the client-side.
 * https://nuxtjs.org/guide/plugins/#name-conventional-plugin
 */
plugins: [{ src: '~/plugins/persistedState.client.js' }]
...
// ~/plugins/persistedState.client.js

import createPersistedState from 'vuex-persistedstate'

export default ({store}) => {
  createPersistedState({
    key: 'yourkey',
    paths: [...]
    ...
  })(store)
}
Using cookies (universal client + server-side)
Add cookie and js-cookie:

npm install --save cookie js-cookie or yarn add cookie js-cookie

// nuxt.config.js
...
plugins: [{ src: '~/plugins/persistedState.js'}]
...
// ~/plugins/persistedState.js

import createPersistedState from 'vuex-persistedstate';
import * as Cookies from 'js-cookie';
import cookie from 'cookie';

export default ({ store, req }) => {
    createPersistedState({
        paths: [...],
        storage: {
            getItem: (key) => {
                // See https://nuxtjs.org/guide/plugins/#using-process-flags
                if (process.server) {
                    const parsedCookies = cookie.parse(req.headers.cookie);
                    return parsedCookies[key];
                } else {
                    return Cookies.get(key);
                }
            },
            // Please see https://github.com/js-cookie/js-cookie#json, on how to handle JSON.
            setItem: (key, value) =>
                Cookies.set(key, value, { expires: 365, secure: false }),
            removeItem: key => Cookies.remove(key)
        }
    })(store);
};
post-custom-banner

0개의 댓글