Skip to content
On this page

useMutationObserver

Category
Export Size
1.18 kB
Last Changed
5 months 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,
    }
  },
}
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: MaybeElementRef,
  callback: MutationCallback,
  options?: UseMutationObserverOptions
): {
  isSupported: Ref<boolean>
  stop: () => void
}
export declare type UseMutationObserverReturn = ReturnType<
  typeof useMutationObserver
>
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: MaybeElementRef,
  callback: MutationCallback,
  options?: UseMutationObserverOptions
): {
  isSupported: Ref<boolean>
  stop: () => void
}
export declare type UseMutationObserverReturn = ReturnType<
  typeof useMutationObserver
>

Source

SourceDemoDocs

Contributors

Anthony Fu
Jelf
AaronBeaudoin
laozei
karma
Shinigami
Alex Kozack
Antério Vieira
zhong666

Changelog

v8.9.3 on 7/14/2022
9b4f9 - fix!: rename type MutationObserverOptions to UseMutationObserverOptions (#1884)
v8.9.2 on 7/12/2022
81d92 - fix(all)!: isSupported becomes Ref instead of boolean for SSR compatibility (#1800)
v8.4.0 on 5/3/2022
a4238 - fix: isSupported misjudge (#1540)

Released under the MIT License.