52
57

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Vue基礎:Vuexの永続化対応

Last updated at Posted at 2019-08-19

Vuexのステートデータを永続化対応しないと、F5とかページreloads操作でデータはなくなります。
一般的に永続化の対応が必要だと思います。

ツールとして、「vuex-persistedstate」がよく使います。

#vuex-persistedstateとは
Persist and rehydrate your Vuex state between page reloads.

#インストール
npm install --save vuex-persistedstate

#storeに設定追加

import createPersistedState from 'vuex-persistedstate'

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

#ストレージの種類
###1. LocalStorage
デフォルトのストレージはlocalstorageです。

###2. SessionStorage

import createPersistedState from 'vuex-persistedstate'

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

###3. Cookies
cookieに保存したい場合は、カスタマイズが必要です。
getItem、setItem、removeItemを実装すればよいです。
下記はCookieに保存するサンプルです。

import { Store } from 'vuex'
import createPersistedState from 'vuex-persistedstate'
import * as Cookies from 'js-cookie'

const store = new Store({
  // ...
  plugins: [
    createPersistedState({
      storage: {
        getItem: key => Cookies.get(key),
        setItem: (key, value) =>
          Cookies.set(key, value, { expires: 7, secure: true }), //7日間有効
        removeItem: key => Cookies.remove(key),
      },
    }),
  ],
})

js-cookies: https://github.com/js-cookie/js-cookie
vuex-persistedstate:https://github.com/robinvdvleuten/vuex-persistedstate

以上

52
57
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
52
57

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?