vue-persistedstate
Version:
state management
50 lines (47 loc) • 1.5 kB
JavaScript
/*
* @Author: zhang_gen_yuan
* @Date: 2022-04-15 18:07:32
* @LastEditTime: 2022-04-26 22:03:01
* @Descripttion:
*/
const setStorage = (key, value, storage) => {
storage.setItem(key, JSON.stringify(value));
};
const getStorage = (key, storage) => {
// return storage.getItem(key) ? JSON.parse(storage.getItem(key)) : {};
const value = storage.getItem(key);
try {
return typeof value !== "undefined" ? JSON.parse(value) : undefined;
} catch (err) {
console.warn(err);
}
return undefined;
};
const createPiniaPersistedState = (options) => {
const key = options && options.key || "pinia";
const storage = options && options.storage || window.localStorage;
return (context) => {
const { store, options } = context;
const whiteList = options.whiteList || [];
const data = getStorage(`${key}-${store.$id}`, storage);
store.$subscribe((patch, state) => {
if (whiteList && whiteList.length !== 0) {
// let newState = JSON.parse(JSON.stringify(state));
let newState = deepClone(state);
let whiteState = {};
for (let i = 0; i < whiteList.length; i++) {
whiteState[whiteList[i]]
? ""
: (whiteState[whiteList[i]] = newState[whiteList[i]]);
setStorage(`${key}-${store.$id}`, whiteState, storage);
}
} else {
setStorage(`${key}-${store.$id}`, state, storage);
}
});
return {
...data,
};
};
};
export default createPiniaPersistedState;