衆所周知,vuex的一個全局狀態管理的插件,可是在瀏覽器刷新的時候,內存中的state會釋放,一般的解決辦法就是用本地存儲的方式保存數據,而後再vuex初始化的時候再賦值給state,手動存再手動取會以爲很麻煩,這個時候就能夠使用vuex的插件vuex-solidification
插件地址: vuex-solidification , 歡迎starvue
vuex有一個hook方法:store.subscribe((mutation, state) => {}) 每次在mutation方法執行完以後都會調用這個回調函數,返回執行完畢以後的stategit
npm install --save vuex-solidification
import Vue from 'vue' import Vuex from 'vuex' import count from './count/index.js'; import createPersistedState from 'vuex-solidification'; Vue.use(Vuex); const store = new Vuex.Store({ state: { count: { value: 0, num: 1 }, pos: 1 } plugins: [ // 默認存儲全部state數據到localstorage createPersistedState() ] });
createPersistedState({options}) : Functiongithub
options裏面能夠有:vuex
key: String 存儲到localStorage, sessionStorage 中對象的key,默認爲vuexnpm
local: Object 和 session: Object, 分別表明localStorage的配置和sessionStorage的配置瀏覽器
local 和 session 裏面能夠有: include: Array 和 exclude: Arraysession
createPersistedState({ local: { include: ['count.value'] } }) /* hook鉤子觸發以後,localstorage裏面存儲的對象爲: { count: { value: 0, } } */ createPersistedState({ local: { exclude: ['count.value'] } }) /* hook鉤子觸發以後,localstorage裏面存儲的對象爲: { count: { num: 1 }, pos: 1 } */ createPersistedState({ session: { include: ['count.value'] } }) /* hook鉤子觸發以後,sessionstorage裏面存儲的對象爲: { count: { value: 0, } } */ createPersistedState({ session: { exclude: ['count.value'] } }) /* hook鉤子觸發以後,sessionstorage裏面存儲的對象爲: { count: { num: 1 }, pos: 1 } */ createPersistedState({ session: { include: ['count'] }, local: { include: ['pos'] } }) /* hook鉤子觸發以後, sessionstorage裏面存儲的對象爲: { count: { value: 0, num: 1 }, } sessionstorage裏面存儲的對象爲: { pos: 0 } */
Check out the example on CodeSandbox.函數
歡迎交流,提issue和pr,