1
import { VNodeDirective } from 'vue'
2

3
type MutateHandler = (
4
  mutationsList: MutationRecord[],
5
  observer: MutationObserver,
6
) => void
7

8
interface MutateVNodeDirective extends Omit<VNodeDirective, 'modifiers'> {
9
  value?: MutateHandler | { handler: MutateHandler, options?: MutationObserverInit }
10
  modifiers?: {
11
    once?: boolean
12
    attr?: boolean
13
    child?: boolean
14
    sub?: boolean
15
    char?: boolean
16
  }
17
}
18

19 1
function inserted (el: HTMLElement, binding: MutateVNodeDirective) {
20 1
  const modifiers = binding.modifiers || {}
21 1
  const value = binding.value
22 1
  const callback = typeof value === 'object' ? value.handler : value!
23 1
  const { once, ...modifierKeys } = modifiers
24 1
  const hasModifiers = Object.keys(modifierKeys).length > 0
25

26
  // Options take top priority
27 1
  const options = typeof value === 'object' && value.options
28 1
    ? value.options
29 1
    : hasModifiers
30
      // If we have modifiers, use only those provided
31 1
      ? {
32
        attributes: modifierKeys.attr,
33
        childList: modifierKeys.child,
34
        subtree: modifierKeys.sub,
35
        characterData: modifierKeys.char,
36
      }
37
      // Defaults to everything on
38 1
      : {
39
        attributes: true,
40
        childList: true,
41
        subtree: true,
42
        characterData: true,
43
      }
44

45 1
  const observer = new MutationObserver((
46
    mutationsList: MutationRecord[],
47
    observer: MutationObserver
48 1
  ) => {
49
    /* istanbul ignore if */
50 1
    if (!el._mutate) return // Just in case, should never fire
51

52 1
    callback(mutationsList, observer)
53

54
    // If has the once modifier, unbind
55 1
    once && unbind(el)
56
  })
57

58 1
  observer.observe(el, options)
59 1
  el._mutate = { observer }
60
}
61

62 1
function unbind (el: HTMLElement) {
63
  /* istanbul ignore if */
64 1
  if (!el._mutate) return
65

66 1
  el._mutate.observer.disconnect()
67 1
  delete el._mutate
68
}
69

70 1
export const Mutate = {
71
  inserted,
72
  unbind,
73
}
74

75
export default Mutate

Read our documentation on viewing source code .

Loading