安装依赖
npm install vuex-persistedstate
使用
import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
/** 用户信息 */
userInfo: {}
},
getters: {
},
mutations: {
},
actions: {},
plugins: [
createPersistedState({
storage: window.sessionStorage
})
]
})
解决JSON.stringify循环依赖的问题
import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'
Vue.use(Vuex)
/** 解决深拷贝问题 */
const getCircularReplacer = () => {
const seen = new WeakSet();
return (key, value) => {
if (typeof value === "object" && value !== null) {
if (seen.has(value)) {
return;
}
seen.add(value);
}
return value;
};
}
export default new Vuex.Store({
state: {
/** 用户信息 */
userInfo: {}
},
getters: {
},
mutations: {
/** 使用示例 */
noteMsg(state, payload) {
state.groupInfo = JSON.parse(JSON.stringify(payload, getCircularReplacer()))
}
},
actions: {},
plugins: [
createPersistedState({
storage: window.sessionStorage
})
]
})
完美解决!