LoginSignup
16
13

More than 5 years have passed since last update.

cookieでvuexのstoreをリロードしても維持する方法

Last updated at Posted at 2018-09-12

vuexを使って開発してると、リロードした時にstateの値がリセットされちゃって辛いことがある。

それを解決するために、一時的にstateの値をcookieやlocal storageに格納し、それがあればその値を取ってくるみたいな処理を書く必要がある。

それなりにめんどくさい。

vuex-persistedstateを使えば、stateの値をcookieやLocal storageに保存できる。

pluginsに読み込めばLocal Storageに保存してくれるようになる。
https://www.npmjs.com/package/vuex-persistedstate

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

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

ただしcookieに保存する場合は容量を考慮する必要がある。

【PHP】Cookieの検証 (保存出来る最大サイズを調べたり、圧縮した文字列をセットしてみたり)をしてみた – 2016年5月

上の記事を読んだところ4095byteを越えるとよくないことが起こる。

僕の場合はstateの値を登録してるつもりがスルーされていた。

4095byteを超えないように、vuex-persistedstateのreducerを使って、保存したいstateの値を明示してあげる。

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


const options = {
  reducer: state => ({
    hoge: state.hoge,
    fuga: state.fuga
  }),
  storage: {
    getItem: key => Cookies.get(key),
    setItem: (key, value) => Cookies.set(key, value, { expires: 365 }),
    removeItem: key => Cookies.remove(key)
  }
}

const store = new Vuex.Store({
  // ...

  plugins: [createPersistedState(options)]
})
16
13
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
16
13