mutationObserver.mjs 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. // Utilities
  2. import { onBeforeUnmount, onMounted, ref, watch } from 'vue';
  3. import { refElement } from "../util/index.mjs"; // Types
  4. export function useMutationObserver(handler, options) {
  5. const mutationRef = ref();
  6. const {
  7. once,
  8. immediate,
  9. ...optionKeys
  10. } = options || {};
  11. const defaultValue = !Object.keys(optionKeys).length;
  12. const observer = new MutationObserver((mutations, observer) => {
  13. handler?.(mutations, observer);
  14. if (options?.once) observer.disconnect();
  15. });
  16. onMounted(() => {
  17. if (!options?.immediate) return;
  18. handler?.([], observer);
  19. });
  20. onBeforeUnmount(() => {
  21. observer.disconnect();
  22. });
  23. watch(mutationRef, (newValue, oldValue) => {
  24. if (oldValue) observer.disconnect();
  25. const el = refElement(newValue);
  26. if (!el) return;
  27. observer.observe(el, {
  28. attributes: options?.attr ?? defaultValue,
  29. characterData: options?.char ?? defaultValue,
  30. childList: options?.child ?? defaultValue,
  31. subtree: options?.sub ?? defaultValue
  32. });
  33. }, {
  34. flush: 'post'
  35. });
  36. return {
  37. mutationRef
  38. };
  39. }
  40. //# sourceMappingURL=mutationObserver.mjs.map