useStorage

vue2-opstions API

在v2中,想要动态存storage

  • watch监听数据
  • add remove内部更新

vue3 -compotions API

  • hooks内部实现
  • 外部监听(代码省略)

useStorage

  1. /*
  2. * @Date: 2021-10-22 14:30:45
  3. * @LastEditTime: 2021-12-08 17:02:48
  4. */
  5. import { judgeTypes } from "utils/index.js";
  6. export function clearAll() {
  7. window.localStorage.clear();
  8. }
  9. /**
  10. * @description: Reset or Add storage
  11. * @param {*} key
  12. * @return {*}
  13. */
  14. export function setData(key, value) {
  15. if (!key) return;
  16. let storageVal = value;
  17. if (judgeTypes(value) !== "string") {
  18. storageVal = JSON.stringify(storageVal);
  19. }
  20. window.localStorage.setItem(key, storageVal);
  21. }
  22. export function getData(key) {
  23. if (!key) return;
  24. if (localStorage.getItem(key)) {
  25. let myData = localStorage.getItem(key);
  26. if (
  27. JSON.parse(localStorage[key]) &&
  28. judgeTypes(JSON.parse(localStorage[key])) === "array"
  29. ) {
  30. return JSON.parse(localStorage[key]);
  31. }
  32. return myData;
  33. } else {
  34. console.warn("当前的key在storage中不存在或者为空值");
  35. return null;
  36. }
  37. }
  38. /**
  39. * @description: clear single data
  40. * @param {*} key
  41. * @return {*}
  42. */
  43. export function removeData(key) {
  44. if (!key) return;
  45. if (localStorage.getItem(key)) localStorage.removeItem(key);
  46. }

vue3 - reacivtiy

  1. import { reactive, effect } from "@vue/reactivity";
  2. export default function useStorage(key, defaultValue = []) {
  3. let data = reactive({});
  4. Object.assign(
  5. data,
  6. (localStorage[key] && JSON.parse(localStorage[key])) || defaultValue
  7. );
  8. effect(() => (localStorage[key] = JSON.stringify(data)));
  9. console.log(data);
  10. return data;
  11. }

优化后代码对比

image.png