Vuex-persistを使用してVuex状態を永続化する
Vuex はアプリの状態を処理するのに最適ですが、複数のページの読み込みなどで状態を維持したい場合があります。 これを行うための素朴な方法(そして私はそれについても罪を犯しています)は、各ミューテーションに簡単な小さな関数呼び出しを追加して、アプリの現在の状態をlocalStorage
に保存することです。 必ずしも優れたソリューションではありませんが、悪くはありません。多くの場合、それで十分です。 しかし、もっと良い方法があります。 Vuex は実際にはプラグインをサポートしており、 vuex-persist は、ストアをlocalStorage
または[X187Xをサポートするその他のストレージ方法と自動的に同期する小さなプラグインです。 ]インターフェース。
インストール
Vue.jsプロジェクトにvuex-persistをインストールします。
# Yarn $ yarn add vuex-persist # or NPM $ npm install vuex-persist --save
使用法
これで、ストアを初期化する場所(これはプロジェクトごとに大きく異なる可能性があります)で、vuex-persist
をインポートし、Vuex
のプラグインとして初期化します。
main.js(部分的)
import Vue from 'vue' import App from 'App.vue'; import Vuex 'vuex'; import VuexPersist from 'vuex-persist'; Vue.use(Vuex); const vuexLocalStorage = new VuexPersist({ key: 'vuex' // The key to store the state on in the storage provider. storage: window.localStorage, // or window.sessionStorage or localForage // Function that passes the state and returns the state with only the objects you want to store. // reducer: state => state, // Function that passes a mutation and lets you decide if it should update the state in localStorage. // filter: mutation => (true) }) const store = new Vuex.Store({ ... plugins: [vuexLocalStorage.plugin] }); ... new Vue({ store, el: '#app', render: h => h(App) });
レデューサーオプションを使用します。
reducer
オプションを使用すると、状態の特定のセクションのみを保存できます。 これは、完全な状態ツリーを渡される単純な関数であり、保持したい状態ツリーの部分のみを含むオブジェクトを返すことが期待されます。 ただし、これによってツリーの構造が変更されないようにする必要があります。そうしないと、ツリーを再ロードできません。
const vuexLocalStorage = new VuexPersist({ storage: window.localStorage, // or window.sessionStorage or localForage instance. // Function that passes the state and returns the state with only the objects you want to store. reducer: state => ({ keepThisModule: state.keepThisModule, keepThisModuleToo: state.keepThisModuleToo // getRidOfThisModule: state.getRidOfThisModule (No one likes it.) }) })
フィルタオプションを使用します。
特定のミューテーションがストアの同期をトリガーしない場合があります。 たとえば、数ミリ秒ごとに呼び出されるミューテーションがある場合、呼び出されるたびにストレージを更新すると、パフォーマンスが大幅に低下します。 vuex-persist
は、この正確なユースケースに対処するためのフィルター機能を提供します。 ストレージの更新を引き起こしたくないミューテーションを除外したり、保持したいミューテーションのホワイトリストを作成したりできます。
const badMutations = [ 'someMutationThatGetsCalledTooOften' ] const vuexLocalStorage = new VuexPersist({ storage: window.localStorage, // or window.sessionStorage or localForage // Function that passes the state and returns the state with only the objects you want to store. // someMutationThatGetsCalledTooOften gets ignored filter: mutation => (badMutations.indexOf(mutation.type) === -1) // Boolean })