diff --git a/packages/core/useStorage/index.test.ts b/packages/core/useStorage/index.test.ts index 51b2e563c3d..0f0e0411113 100644 --- a/packages/core/useStorage/index.test.ts +++ b/packages/core/useStorage/index.test.ts @@ -1,5 +1,5 @@ import { debounceFilter, promiseTimeout } from '@vueuse/shared' -import { isVue3, ref } from 'vue-demi' +import { isVue3, nextTick, ref } from 'vue-demi' import { nextTwoTick, useSetup } from '../../.test' import { useStorage } from '.' @@ -358,4 +358,23 @@ describe('useStorage', () => { const customRef2 = useStorage(KEY, 2, storage, { mergeDefaults: (value, initial) => value + initial }) expect(customRef2.value).toEqual(3) }) + + it('sync several refs', async () => { + storage.setItem(KEY, '0') + + const first = useStorage(KEY, 0, storage) + const second = useStorage(KEY, 1, storage) + + expect(first.value).toBe(0) + expect(second.value).toBe(0) + + await nextTick() + + first.value = 5 + + await nextTick() + + expect(first.value).toBe(5) + expect(second.value).toBe(5) + }) }) diff --git a/packages/core/useStorage/index.ts b/packages/core/useStorage/index.ts index f2ca68b9e52..e4ecce83589 100644 --- a/packages/core/useStorage/index.ts +++ b/packages/core/useStorage/index.ts @@ -160,19 +160,34 @@ export function useStorage { flush, deep, eventFilter }, ) - if (window && listenToStorageChanges) + const CUSTOM_EVENT = '_vueuse_storage' + + if (window && listenToStorageChanges) { + // The storage event is not working with the same document. useEventListener(window, 'storage', update) + useEventListener(window, CUSTOM_EVENT, update) + } update() return data function write(v: unknown) { + let newValue: null | string = null + try { - if (v == null) - storage!.removeItem(key) - else - storage!.setItem(key, serializer.write(v)) + if (v == null) { storage!.removeItem(key) } + else { + newValue = serializer.write(v) + + storage!.setItem(key, newValue) + } + + if (window && listenToStorageChanges) { + const event = new StorageEvent(CUSTOM_EVENT, { key, newValue }) + + window.dispatchEvent(event) + } } catch (e) { onError(e)