自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Vue3優(yōu)雅地監(jiān)聽localStorage變化

開發(fā) 前端
原生的localStorage?只能監(jiān)聽同源地址下不同頁面的localStorage?變化,作為單頁面應(yīng)用,顯然不實(shí)用。所以我打算自定義一個(gè)hook?監(jiān)聽localStorage的變化。

最近在研究框架,也仔細(xì)用了Vue3一些功能,今天分享一次我的實(shí)踐:

「Vue3如何監(jiān)聽localStorage的變化?!?/p>

?? 為什么要這樣做?

原生的localStorage只能監(jiān)聽同源地址下不同頁面的localStorage變化,作為單頁面應(yīng)用,顯然不實(shí)用。所以我打算自定義一個(gè)hook監(jiān)聽localStorage的變化。

?? 思路

首先我們需要重寫localStorage下的所有方法,這樣在每個(gè)方法被使用的時(shí)候就可以被監(jiān)聽到了。

此時(shí)就需要一個(gè)事件機(jī)制,用于傳遞消息。

在Vue3移除了$on、$emit事件接口后,我們可以借助第三方庫實(shí)現(xiàn):mitt、tiny-emitter.

不過我打算使用自己實(shí)現(xiàn)的中介者模式作為通信方法。

?? 實(shí)現(xiàn)

?? 實(shí)現(xiàn)中介者模式

// mediator.ts
export interface MediatorProps {
  uuid?: number;
  publish?: (topic: string, ...args: unknown[]) => void;
  subscribe?: (topic: string, callback: (...args: unknown[]) => void) => void;
}

const mediator = (function () {
  let topics = [],
    uuid = 0;

  function subscribe(topic: string, callback: (...args: unknown[]) => void) {
    uuid++;
    topics[topic] = topics[topic]
      ? [...topics[topic], { callback, uuid }]
      : [{ callback, uuid }];
  }

  function publish(topic: string, ...args: unknown[]) {
    if (topics[topic]) {
      topics[topic].map((item) => item.callback(...args));
    }
  }
  return {
    install: function (obj: MediatorProps) {
      obj.uuid = uuid;
      obj.publish = publish;
      obj.subscribe = subscribe;
      return obj;
    },
  };
})();

export default mediator;

?? 重寫localStorage

// localStorage.ts
import mediator from "./mediator";

const keys: string[] = [];

const createMediator = () => mediator.install({});

const sub = createMediator();

export const $localStorage = {
  getItem: (key: string) => {
    return window.localStorage.getItem(key);
  },

  setItem: (key: string, value: any) => {
    // 防止重復(fù)發(fā)布
    if (!keys.includes(key)) keys.push(key);

    // 被修改就發(fā)布事件
    sub.publish(key, value);    

    window.localStorage.setItem(key, value);
  },
  clear: () => {
    // 被刪除就每個(gè)key發(fā)布事件
    keys.map((key) => sub.publish(key, undefined));
    // 發(fā)布后清空記錄key的數(shù)組
    keys.length = 0;

    window.localStorage.clear();
  },
  removeItem: (key: string) => {
    keys.splice(keys.indexOf(key), 1);

    // 被移除就發(fā)布 undefined
    sub.publish(key, undefined);

    window.localStorage.removeItem(key);
  },
  key: window.localStorage.key,
  length: window.localStorage.length,
};

?? 實(shí)現(xiàn)useStorage hook

// useStorage.ts
import { ref } from "vue";
import mediator from "./mediator";
const createMediator = () => mediator.install({});

 export const useStorage = (key: string) => {
  
  const string = ref(null);

  const sub = createMediator();

  sub.subscribe(key, (value) => string.value = value);

  return string;
};

?? 測(cè)試

?? 使用localStorage

// One.vue
// 使用localStorage
import { watch } from "vue";
import { useStorage } from "./hook";

const key = useStorage("yourKey");

watch([key], (a) => console.log(a));

?? 監(jiān)聽localStorage變化

// Two.vue
// 監(jiān)聽localStorage
<script setup lang="ts">
import { ref } from "vue";
import { localStorage } from "./hook";

const count = ref(0);
</script>

<template>
  <div>
      <button
        type="button"
        @click="$localStorage.setItem('a', count++);"
      >
        count is {{ count }}
      </button>
    </div>
</template>

?? 結(jié)果

圖片

打印結(jié)果

好了今天的分享的就到了,希望今天的分享可以幫助到你!

源碼點(diǎn)這里:https://codesandbox.io/p/sandbox/hardcore-hodgkin-qp5lwu

責(zé)任編輯:武曉燕 來源: 萌萌噠草頭將軍
相關(guān)推薦

2023-12-11 18:20:21

Vue.js事件機(jī)制傳遞

2023-12-14 08:25:14

WatchVue.js監(jiān)聽數(shù)據(jù)

2022-11-01 11:55:27

ReactVue3

2021-12-01 08:11:44

Vue3 插件Vue應(yīng)用

2021-11-17 08:24:47

Vue3 插件Vue應(yīng)用

2021-11-30 08:19:43

Vue3 插件Vue應(yīng)用

2023-11-28 09:03:59

Vue.jsJavaScript

2022-06-29 16:59:21

Vue3Vue2面試

2024-04-10 10:15:16

監(jiān)聽

2020-09-19 21:15:26

Composition

2023-11-16 08:29:26

2021-09-03 08:23:21

Vue 插槽子組件

2021-12-02 05:50:35

Vue3 插件Vue應(yīng)用

2021-05-26 10:40:28

Vue3TypeScript前端

2021-11-16 08:50:29

Vue3 插件Vue應(yīng)用

2022-03-10 11:04:04

Vue3Canvas前端

2021-12-08 09:09:33

Vue 3 Computed Vue2

2024-11-06 10:16:22

2022-06-21 12:09:18

Vue差異

2015-08-13 15:56:44

HTML5本地存儲(chǔ)Localstorag
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)