From f9136e85806881a7d3163afe7c4d9d0d78271abb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=B6=E8=BF=9C=E6=96=B9?= Date: Thu, 9 Nov 2023 23:55:45 +0800 Subject: [PATCH] feat(useMutationObserver): add `takeRecords` function (#3480) --- .../core/useMutationObserver/index.test.ts | 21 +++++++++++++++++++ packages/core/useMutationObserver/index.ts | 5 +++++ 2 files changed, 26 insertions(+) diff --git a/packages/core/useMutationObserver/index.test.ts b/packages/core/useMutationObserver/index.test.ts index d91c77cd604..9cc75ca5570 100644 --- a/packages/core/useMutationObserver/index.test.ts +++ b/packages/core/useMutationObserver/index.test.ts @@ -166,4 +166,25 @@ describe('useMutationObserver', () => { await promiseTimeout(10) expect(cb).toHaveBeenCalledTimes(1) }) + + it('should work with takeRecords', async () => { + const target = document.createElement('div') + const cb = vi.fn() + + const { takeRecords } = useMutationObserver(target, cb, { + attributes: true, + }) + + target.setAttribute('id', 'footer') + await promiseTimeout(10) + expect(cb).toHaveBeenCalledTimes(1) + + target.setAttribute('id', 'header') + const records = takeRecords() + + await promiseTimeout(10) + expect(records).toHaveLength(1) + expect(records![0].target).toBe(target) + expect(cb).toHaveBeenCalledTimes(1) + }) }) diff --git a/packages/core/useMutationObserver/index.ts b/packages/core/useMutationObserver/index.ts index 94201515807..f17a01db1ca 100644 --- a/packages/core/useMutationObserver/index.ts +++ b/packages/core/useMutationObserver/index.ts @@ -46,6 +46,10 @@ export function useMutationObserver( { immediate: true }, ) + const takeRecords = () => { + return observer?.takeRecords() + } + const stop = () => { cleanup() stopWatch() @@ -56,6 +60,7 @@ export function useMutationObserver( return { isSupported, stop, + takeRecords, } }