1、背景
vuex可以進行全局的狀態(tài)管理,但刷新后刷新后數(shù)據(jù)會消失,使用vuex-persistedstate可以對部分數(shù)據(jù)進行數(shù)據(jù)持久化,刷新后數(shù)據(jù)不消失。
- vuex-persistedstate存儲數(shù)據(jù)默認方式為localStorage, localStorage 用于長久保存整個網站的數(shù)據(jù),保存的數(shù)據(jù)沒有過期時間,直到手動去刪除,且localStorage屬性是只讀的。
- 如果你只想將數(shù)據(jù)保存在當前會話中,可以使用sessionStorage屬性, 該數(shù)據(jù)對象臨時保存同一窗口(或標簽頁)的數(shù)據(jù),在關閉窗口或標簽頁之后將會刪除這些數(shù)據(jù)。
詳細了解查看官網 組件github官網
本文章使用localStorage,sessionStorage進行數(shù)據(jù)持久化
2、安裝插件vuex-persistedstate
yarn add vuex-persistedstate
3、配置vuex-persistedstate組件-store/index.js文件內修改
//持久化插件
import createPersistedState from 'vuex-persistedstate';
4、使用方式-store/index.js文件內修改,modules內state進行持久化使用
//store/login/login.js
const login = {
state: {
isLogin: false,
userInfo: {}
},
getters: {},
actions: {},
mutations: {}
};
export default login;
paths給定路徑,可以指定持久化的具體數(shù)據(jù) 未給出路徑完成狀態(tài)保存
//舉例此為登錄的store文件
import login from '@/store/login/login';
//localStorage緩存,需要手動刪除或者重新賦值才會修改
const vuexLocal = createPersistedState({
key: 'vuexLocal',
storage: window.localStorage,
paths: ['login.isLogin']
});
//會話關掉,數(shù)據(jù)清空
const vuexSession = createPersistedState({
key: 'vuexsession',
storage: window.sessionStorage,
paths: ['login.userInfo']
});
export default new Vuex.Store({
state: {},
mutations: {},
getters: {},
actions: {},
modules: {
login
},
plugins: [vuexLocal, vuexSession]
});
5、在f12審查的Application內可以看到

vuexSession

vuexLocal