forked from vueComponent/ant-design-vue
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseMutationObserver.ts
62 lines (53 loc) · 1.61 KB
/
useMutationObserver.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import { tryOnScopeDispose } from './tryOnScopeDispose';
import { watch } from 'vue';
import type { MaybeElementRef } from './unrefElement';
import { unrefElement } from './unrefElement';
import { useSupported } from './useSupported';
import type { ConfigurableWindow } from './_configurable';
import { defaultWindow } from './_configurable';
export interface UseMutationObserverOptions extends MutationObserverInit, ConfigurableWindow {}
/**
* Watch for changes being made to the DOM tree.
*
* @see https://vueuse.org/useMutationObserver
* @see https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver MutationObserver MDN
* @param target
* @param callback
* @param options
*/
export function useMutationObserver(
target: MaybeElementRef,
callback: MutationCallback,
options: UseMutationObserverOptions = {},
) {
const { window = defaultWindow, ...mutationOptions } = options;
let observer: MutationObserver | undefined;
const isSupported = useSupported(() => window && 'MutationObserver' in window);
const cleanup = () => {
if (observer) {
observer.disconnect();
observer = undefined;
}
};
const stopWatch = watch(
() => unrefElement(target),
el => {
cleanup();
if (isSupported.value && window && el) {
observer = new MutationObserver(callback);
observer!.observe(el, mutationOptions);
}
},
{ immediate: true },
);
const stop = () => {
cleanup();
stopWatch();
};
tryOnScopeDispose(stop);
return {
isSupported,
stop,
};
}
export type UseMutationObserverReturn = ReturnType<typeof useMutationObserver>;