$ npm install vuex-persistedstate -S
import persistedState from 'vuex-persistedstate' const store = new Vuex.Store({ // ... plugins: [persistedState()] })
vuex-persistedstate
默认使用localStorage储存,若想使用sessionStorage,可采用以下配置
import persistedState from "vuex-persistedstate" const store = new Vuex.Store({ // ... plugins: [persistedState ({ storage: window.sessionStorage })] })
$ npm install js-cookie -S
import Cookies from 'js-cookie'; import persistedState from "vuex-persistedstate" const store = new Vuex.Store({ // ... plugins: [persistedState ({ storage: { getItem: key => Cookies.get(key), setItem: (key, value) => Cookies.set(key, value), removeItem: key => Cookies.remove(key) } })] })
vuex-persistedstate
插件,vuex-persistedstate
是没有加密的,用户的信息就暴露在缓存中,secure-ls
来加密storage$ npm install secure-ls -S
import Vue from "vue"; import Vuex from "vuex"; import SecureLS from 'secure-ls'; import persistedState from "vuex-persistedstate"; const ls = new SecureLS({ encodingType: "aes", // 加密方式 isCompression: false, // 是否启用数据压缩 encryptionSecret: "old-beauty" // }); Vue.use(Vuex); export default new Vuex.Store({ ... plugins: [persistedState({ // key: "123123", // 存入storage是的key storage: { getItem: key => ls.get(key), setItem: (key, value) => ls.set(key, value), removeItem: key => ls.remove(key) } })], });
【注】vuex-persist(不兼容ie) vuex-persistedstate