$ npm install vuex-persistedstate --save-dev
import createPersistedState from 'vuex-persistedstate' const store = new Vuex.Store({ // ...这样配置表示把VUEX中的全部数据存到localStorage中
plugins: [createPersistedState()]
})
createPersistedState([options])
使用给定的选项建立插件的新实例。能够提供如下选项来配置您的特定需求的插件:vue
key <String>
:存储持久状态的键。(默认:vuex)git
paths <Array>
:部分持续状态的任何路径的数组。若是没有路径给出,完整的状态是持久的。(默认:[])github
reducer <Function>
:一个函数,将被调用来减小基于给定的路径持久化的状态。默认包含这些值。vuex
subscriber <Function>
:一个被调用来设置突变订阅的函数。默认为store => handler => store.subscribe(handler)
npm
storage <Object>
:而不是(或与)getState
和setState
。默认为localStorage。数组
getState <Function>
:将被调用以从新水化先前持久状态的函数。默认使用storage
。promise
setState <Function>
:将被调用来保持给定状态的函数。默认使用storage
。bash
filter <Function>
:将被调用来过滤将setState
最终触发存储的任何突变的函数。默认为() => true
服务器
若是在本地存储中存储Vuex存储的状态并不理想。人们能够轻松地实现功能使用cookie(或任何其余你能够想到的);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: 3, secure: true }), removeItem: key => Cookies.remove(key) } }) ] })
实际上,能够传递任何遵循存储协议(getItem,setItem,removeItem等)的对象:
createPersistedState({ storage: window.sessionStorage })
当你将这个插件与服务器端渲染结合使用时,这是很是有用的,在这里能够传递一个dom-storage的实例。
由于它可能看起来乍一看,它不可能做为属性传递一个LocalForage实例storage
。这是由于全部的getter和setter必须是同步的,LocalForage的方法是异步的。