Skip to content
On this page

useMutationObserver

Category
Last Changed
3 months ago

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

Demo

Usage

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,
    }
  },
}
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

export interface MutationObserverOptions
  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: MaybeElementRef,
  callback: MutationCallback,
  options?: MutationObserverOptions
): {
  isSupported: boolean | undefined
  stop: () => void
}
export declare type UseMutationObserverReturn = ReturnType<
  typeof useMutationObserver
>
export interface MutationObserverOptions
  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: MaybeElementRef,
  callback: MutationCallback,
  options?: MutationObserverOptions
): {
  isSupported: boolean | undefined
  stop: () => void
}
export declare type UseMutationObserverReturn = ReturnType<
  typeof useMutationObserver
>

Source

SourceDemoDocs

Contributors

Anthony Fu
Shinigami
Alex Kozack
Antério Vieira
zhong666

Changelog

v6.0.0-beta.2 on 8/9/2021
ff21b - feat: use tryOnScopeDispose instead of tryOnUnmounted
v4.11.2 on 5/30/2021
68c7d - feat(typedef): add return typedefs (#543) (#544)
useMutationObserver has loaded