欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

業(yè)務(wù)層hooks封裝useSessionStorage實(shí)例詳解

 更新時間:2022年08月19日 11:57:09   作者:大耳朵瓜子  
這篇文章主要為大家介紹了業(yè)務(wù)層hooks封裝useSessionStorage實(shí)例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪

封裝原因:

名稱:useSessionStorage

功能開發(fā)過程中,需要進(jìn)行數(shù)據(jù)的臨時存儲,正常情況下,使用localStorage或者 sessionStorage,存在于 window 對象中,使用場景不一樣。

sessionStorage的生命周期是在瀏覽器關(guān)閉前,瀏覽器關(guān)閉后自動清理,頁面刷新不會清理。

localStorage的生命周期是永久性的,存儲的數(shù)據(jù)需要手動刪除。

建議:

  • 存儲業(yè)務(wù)數(shù)據(jù),登錄會話內(nèi),使用sessionStorage。
  • 需要持久化話的數(shù)據(jù),比如token標(biāo)記之類的可以使用localStorage,使用時需要謹(jǐn)慎對待,以及考慮清理時機(jī)。

工具庫封裝模式:

工具庫目錄:

API設(shè)計:

  • 獲取本地存儲 getCache
  • 寫入本地存儲 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('無法獲取用戶信息!');
    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('無法獲取用戶信息!');
    return;
  }
  return setCache(`${id}-${key}`, value, type);
}
function removeCookies(key) {
  key && Cookie.remove(key);
}
export default {
  getCache,
  setCache,
  getUserCache,
  setUserCache,
  removeCookies
};

以上設(shè)計屬于框架層,提供操作本地存儲的能力,但是為什么業(yè)務(wù)側(cè)需要封裝hooks呢?

主要原因:

使用起來有點(diǎn)麻煩,需要import引入工具庫,但是hooks使用也需要import引入,因?yàn)楣δ茼撁娲蟛糠忠氲亩际莌ooks,使用解構(gòu),代碼量就會縮減,而且使用認(rèn)知會減少,引入hooks即可,“你需要用到的都在hooks里面”

Hooks設(shè)計方式

那我們開始設(shè)計

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)聽
  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,導(dǎo)出一個響應(yīng)式的state, 用戶直接賦值state.value可自動修改本地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ù)說明類型默認(rèn)值
keysessionStorage存儲鍵名any-
initialValue初始值any{}
options配置Options-

Options

參數(shù)說明類型默認(rèn)值
watch是否實(shí)時修改sessionStoragebooleantrue

Result

參數(shù)說明類型
state可以被修改的數(shù)據(jù)源Ref

總結(jié):

這種使用方式,是針對業(yè)務(wù)側(cè)vue3的,自帶響應(yīng)式綁定,和使用 Ref一樣,利用.value進(jìn)行獲取和賦值。

以上就是業(yè)務(wù)層hooks封裝useSessionStorage實(shí)例詳解的詳細(xì)內(nèi)容,更多關(guān)于hooks封裝useSessionStorage的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評論