業(yè)務(wù)層hooks封裝useSessionStorage實(shí)例詳解
封裝原因:
名稱:useSessionStorage
功能開(kāi)發(fā)過(guò)程中,需要進(jìn)行數(shù)據(jù)的臨時(shí)存儲(chǔ),正常情況下,使用localStorage或者 sessionStorage,存在于 window 對(duì)象中,使用場(chǎng)景不一樣。
sessionStorage的生命周期是在瀏覽器關(guān)閉前,瀏覽器關(guān)閉后自動(dòng)清理,頁(yè)面刷新不會(huì)清理。
localStorage的生命周期是永久性的,存儲(chǔ)的數(shù)據(jù)需要手動(dòng)刪除。
建議:
- 存儲(chǔ)業(yè)務(wù)數(shù)據(jù),登錄會(huì)話內(nèi),使用sessionStorage。
- 需要持久化話的數(shù)據(jù),比如token標(biāo)記之類的可以使用localStorage,使用時(shí)需要謹(jǐn)慎對(duì)待,以及考慮清理時(shí)機(jī)。
工具庫(kù)封裝模式:
工具庫(kù)目錄:
API設(shè)計(jì):
- 獲取本地存儲(chǔ) getCache
- 寫(xiě)入本地存儲(chǔ) setCache
- 設(shè)置用戶緩存 setUserCache
- 獲取用戶緩存getUserCache
- 移除cookie removeCookies
代碼實(shí)踐:
import Cookie from 'js-cookie'; /** * 獲取緩存數(shù)據(jù) * @param {string} key * @param {string} type: 緩存類型 'local'(默認(rèn)) / 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; } /** * 獲取緩存數(shù)據(jù) * @param {string} key * @param {any} value * @param {string} type: 緩存類型 'local'(默認(rèn)) / 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('無(wú)法獲取用戶信息!'); return; } return getCache(`${id}-${key}`, type); } /** * 設(shè)置用戶緩存 * @param {*} key * @param {*} value * @param {*} type */ function setUserCache(key, value, type = 'local') { const id = getCache('userId', 'session'); if (!id) { console.error('無(wú)法獲取用戶信息!'); return; } return setCache(`${id}-${key}`, value, type); } function removeCookies(key) { key && Cookie.remove(key); } export default { getCache, setCache, getUserCache, setUserCache, removeCookies };
以上設(shè)計(jì)屬于框架層,提供操作本地存儲(chǔ)的能力,但是為什么業(yè)務(wù)側(cè)需要封裝hooks呢?
主要原因:
使用起來(lái)有點(diǎn)麻煩,需要import引入工具庫(kù),但是hooks使用也需要import引入,因?yàn)楣δ茼?yè)面大部分引入的都是hooks,使用解構(gòu),代碼量就會(huì)縮減,而且使用認(rèn)知會(huì)減少,引入hooks即可,“你需要用到的都在hooks里面”
Hooks設(shè)計(jì)方式
那我們開(kāi)始設(shè)計(jì)
useSessionStorage.js
import { ref, Ref, isRef, watch as vueWatch } from "vue"; const storage = sessionStorage; const defaultOptions = { watch: true } /** * 獲取數(shù)據(jù)類型 * @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"; }; /** * 按照類型格式數(shù)據(jù)的常量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)); // 狀態(tài)監(jiān)聽(tīng) if (watch) { vueWatch( data, (newValue) => { if (newValue === undefined || newValue === null) { storage.removeItem(key); return; } setStorage(); }, { deep: true, } ); } setStorage(); return data; }; export default useSessionStorage;
簡(jiǎn)介:
useSessionStorage接受一個(gè)key和一個(gè)value,導(dǎo)出一個(gè)響應(yīng)式的state, 用戶直接賦值state.value可自動(dòng)修改本地sessionStorage。
注意點(diǎn)
- 不設(shè)置value可用于獲取本地sessionStorage 例:
useSessionStorage('useSessionStorage')
- value等于undefined或者null可用于刪除本地Storage 例:
state.value = undefined;
Api
const state = useSessionStorage( key: string, initialValue?: any, options?: Options );
Params
參數(shù) | 說(shuō)明 | 類型 | 默認(rèn)值 |
---|---|---|---|
key | sessionStorage存儲(chǔ)鍵名 | any | - |
initialValue | 初始值 | any | {} |
options | 配置 | Options | - |
Options
參數(shù) | 說(shuō)明 | 類型 | 默認(rèn)值 |
---|---|---|---|
watch | 是否實(shí)時(shí)修改sessionStorage | boolean | true |
Result
參數(shù) | 說(shuō)明 | 類型 |
---|---|---|
state | 可以被修改的數(shù)據(jù)源 | Ref |
總結(jié):
這種使用方式,是針對(duì)業(yè)務(wù)側(cè)vue3的,自帶響應(yīng)式綁定,和使用 Ref一樣,利用.value進(jìn)行獲取和賦值。
以上就是業(yè)務(wù)層hooks封裝useSessionStorage實(shí)例詳解的詳細(xì)內(nèi)容,更多關(guān)于hooks封裝useSessionStorage的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
- VUE使用localstorage和sessionstorage實(shí)現(xiàn)登錄示例詳解
- vue如何使用cookie、localStorage和sessionStorage進(jìn)行儲(chǔ)存數(shù)據(jù)
- ahooks封裝cookie?localStorage?sessionStorage方法
- JavaScript中本地存儲(chǔ)(LocalStorage)和會(huì)話存儲(chǔ)(SessionStorage)的使用
- vue中LocalStorage與SessionStorage的區(qū)別與用法
- sessionStorage存儲(chǔ)時(shí)多窗口之前能否進(jìn)行狀態(tài)共享解析
相關(guān)文章
詳解如何發(fā)布TypeScript編寫(xiě)的npm包
這篇文章主要介紹了如何發(fā)布TypeScript編寫(xiě)的npm包實(shí)現(xiàn)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-12-12JavaScript中七種流行的開(kāi)源機(jī)器學(xué)習(xí)框架
今天小編就為大家分享一篇關(guān)于JavaScript中五種流行的開(kāi)源機(jī)器學(xué)習(xí)框架,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧2018-10-10Intersection?Observer交叉觀察器示例解析
這篇文章主要為大家介紹了Intersection?Observer交叉觀察器示例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-02-02微信小程序 高德地圖SDK詳解及簡(jiǎn)單實(shí)例(源碼下載)
這篇文章主要介紹了微信小程序 高德地圖詳解及簡(jiǎn)單實(shí)例(源碼下載)的相關(guān)資料,需要的朋友可以參考下2017-01-01微信小程序本地緩存數(shù)據(jù)增刪改查實(shí)例詳解
這篇文章主要介紹了微信小程序本地緩存數(shù)據(jù)增刪改查實(shí)例詳解的相關(guān)資料,需要的朋友可以參考下2017-05-05js類型判斷內(nèi)部實(shí)現(xiàn)原理示例詳解
這篇文章主要為大家介紹了js類型判斷內(nèi)部實(shí)現(xiàn)原理示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-07-075種 JavaScript 方式實(shí)現(xiàn)數(shù)組扁平化
這篇文章主要介紹5種 JavaScript 方式實(shí)現(xiàn)數(shù)組扁平化,雖說(shuō)只有5種方法,但是核心只有一個(gè)就是遍歷數(shù)組arr,若arr[i]為數(shù)組則遞歸遍歷,直至arr[i]不為數(shù)組然后與之前的結(jié)果concat。 想具體了解的小伙伴那請(qǐng)看下面文章內(nèi)容吧2021-09-09