名称:useSessionStorage
功能开发过程中,需要进行数据的临时存储,正常情况下,使用localStorage或者 sessionStorage,存在于 window 对象中,使用场景不一样。
sessionStorage的生命周期是在浏览器关闭前,浏览器关闭后自动清理,页面刷新不会清理。
localStorage的生命周期是永久性的,存储的数据需要手动删除。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 |
import Cookie from 'js-cookie'; /** * 获取缓存数据 * @param {string} key * @param {string} type: 缓存类型 'local'(默认) / cookie / session; */ function getCache(key, type = 'local') { let data; switch (type) { case 'cookie': data = Cookie.get(key); break; case 'session': // eslint-disable-next-line no-case-declarations let strS = sessionStorage.getItem(key); try { data = JSON.parse(strS); } catch (e) { data = strS; } break; default: // eslint-disable-next-line no-case-declarations let strL = localStorage.getItem(key); try { data = JSON.parse(strL); } catch (e) { data = strL; } break; } return data; } /** * 获取缓存数据 * @param {string} key * @param {any} value * @param {string} type: 缓存类型 'local'(默认) / cookie / session; */ function setCache(key, value, type = 'local') { switch (type) { case 'cookie': Cookie.set(key, value, { expires: 7 }); break; case 'session': sessionStorage.setItem(key, JSON.stringify(value)); break; default: localStorage.setItem(key, JSON.stringify(value)); break; } } /** * 获取用户缓存 * @param {*} key * @param {*} type */ function getUserCache(key, type = 'local') { const id = getCache('userId', 'session'); if (!id) { console.error('无法获取用户信息!'); return; } return getCache(`${id}-${key}`, type); } /** * 设置用户缓存 * @param {*} key * @param {*} value * @param {*} type */ function setUserCache(key, value, type = 'local') { const id = getCache('userId', 'session'); if (!id) { console.error('无法获取用户信息!'); return; } return setCache(`${id}-${key}`, value, type); } function removeCookies(key) { key && Cookie.remove(key); } export default { getCache, setCache, getUserCache, setUserCache, removeCookies }; |
以上设计属于框架层,提供操作本地存储的能力,但是为什么业务侧需要封装hooks呢?
主要原因:
使用起来有点麻烦,需要import引入工具库,但是hooks使用也需要import引入,因为功能页面大部分引入的都是hooks,使用解构,代码量就会缩减,而且使用认知会减少,引入hooks即可,“你需要用到的都在hooks里面”
那我们开始设计
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 |
import { ref, Ref, isRef, watch as vueWatch } from "vue"; const storage = sessionStorage; const defaultOptions = { watch: true } /** * 获取数据类型 * @param defaultValue * @returns */ const getValueType = (defaultValue) => { return defaultValue == null ? "any" : typeof defaultValue === "boolean" ? "boolean" : typeof defaultValue === "string" ? "string" : typeof defaultValue === "object" ? "object" : Array.isArray(defaultValue) ? "object" : !Number.isNaN(defaultValue) ? "number" : "any"; }; /** * 按照类型格式数据的常量Map */ const TypeSerializers = { boolean: { read: (v) => (v != null ? v === "true" : null), write: (v) => String(v), }, object: { read: (v) => (v ? JSON.parse(v) : null), write: (v) => JSON.stringify(v), }, number: { read: (v) => (v != null ? Number.parseFloat(v) : null), write: (v) => String(v), }, any: { read: (v) => (v != null && v !== "null" ? v : null), write: (v) => String(v), }, string: { read: (v) => (v != null ? v : null), write: (v) => String(v), }, }; /** * 缓存操作 */ const useSessionStorage = (key, initialValue, options) => { const { watch } = { ...defaultOptions, ...options }; const data = ref(null); try { if (initialValue !== undefined) { data.value = isRef(initialValue) ? initialValue.value : initialValue; } else { data.value = JSON.parse(storage.getItem(key) || "{}"); } } catch (error) { console.log(error, "useLocalStorage初始化失败"); } const type = getValueType(data.value); // 判断类型取格式化方法 let serializer = TypeSerializers[type]; const setStorage = () => storage.setItem(key, serializer.write(data.value)); // 状态监听 if (watch) { vueWatch( data, (newValue) => { if (newValue === undefined || newValue === null) { storage.removeItem(key); return; } setStorage(); }, { deep: true, } ); } setStorage(); return data; }; export default useSessionStorage; |
useSessionStorage接受一个key和一个value,导出一个响应式的state, 用户直接赋值state.value可自动修改本地sessionStorage。
1 2 3 4 5 |
const state = useSessionStorage( key: string, initialValue?: any, options?: Options ); |
参数 | 说明 | 类型 | 默认值 |
---|---|---|---|
key | sessionStorage存储键名 | any | - |
initialValue | 初始值 | any | {} |
options | 配置 | Options | - |
参数 | 说明 | 类型 | 默认值 |
---|---|---|---|
watch | 是否实时修改sessionStorage | boolean | true |
参数 | 说明 | 类型 |
---|---|---|
state | 可以被修改的数据源 | Ref |
这种使用方式,是针对业务侧vue3的,自带响应式绑定,和使用 Ref一样,利用.value进行获取和赋值。