Skip to content

useMutationObserver ​

Category
Export Size
613 B
Last Changed
3 weeks ago

Watch for changes being made to the DOM tree. MutationObserver MDN

Demo ​

Usage ​

ts
import { ref } from 'vue'
import { useMutationObserver } from '@vueuse/core'

export default {
  setup() {
    const el = ref(null)
    const messages = ref([])

    useMutationObserver(el, (mutations) => {
      if (mutations[0])
        messages.value.push(mutations[0].attributeName)
    }, {
      attributes: true,
    })

    return {
      el,
      messages,
    }
  },
}

Type Declarations ​

typescript
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 declare function useMutationObserver(
  target:
    | MaybeComputedElementRef
    | MaybeComputedElementRef[]
    | MaybeRefOrGetter<MaybeElement[]>,
  callback: MutationCallback,
  options?: UseMutationObserverOptions,
): {
  isSupported: ComputedRef<boolean>
  stop: () => void
  takeRecords: () => MutationRecord[] | undefined
}
export type UseMutationObserverReturn = ReturnType<typeof useMutationObserver>

Source ​

Source • Demo • Docs

Contributors ​

Anthony Fu
丶远方
Jelf
jdm1219
chirokas
huodoushigemi
AaronBeaudoin
laozei
karma
Shinigami
Alex Kozack
Antério Vieira
zhong666

Changelog ​

v10.8.0 on 2/20/2024
98fac - feat: allow multiple targets (#3741)
v10.6.0 on 11/9/2023
f9136 - feat: add takeRecords function (#3480)
v10.5.0 on 10/7/2023
8167b - feat: use MaybeComputedElementRef (#3430)
v8.9.3 on 7/14/2022
9b4f9 - fix!: rename type MutationObserverOptions to UseMutationObserverOptions (#1884)

Released under the MIT License.