Skip to content

⬅️ Back to Table of Contents

πŸ“„ watchArray

πŸ“Š Analysis Summary

Metric Count
πŸ”§ Functions 1
πŸ“¦ Imports 4
🟒 Vue Composition API 1
πŸ“‘ Type Aliases 1

πŸ“š Table of Contents

πŸ› οΈ File Location:

πŸ“‚ packages/shared/watchArray/index.ts

πŸ“¦ Imports

Name Source
WatchOptions vue
WatchSource vue
toValue vue
watch vue

Vue Composition API

Name Type Reactive Variables Composables
watch watch none none

Functions

watchArray(source: WatchSource<T[]> | T[], cb: WatchArrayCallback<T[], Immediate exten…, options: WatchOptions<Immediate>): any

Watch for an array with additions and removals.

See: https://vueuse.org/watchArray

Raw JSDoc
/**
 * Watch for an array with additions and removals.
 *
 * @see https://vueuse.org/watchArray
 */

Calls:

  • source
  • Array.isArray
  • toValue (from vue)
  • watch (from vue)
  • Array.from
  • added.push
  • oldList.filter
  • cb
Code
export function watchArray<T, Immediate extends Readonly<boolean> = false>(
  source: WatchSource<T[]> | T[],
  cb: WatchArrayCallback<T[], Immediate extends true ? T[] | undefined : T[]>,
  options?: WatchOptions<Immediate>,
) {
  let oldList: T[] = options?.immediate
    ? []
    : [...(typeof source === 'function'
        ? source()
        : Array.isArray(source)
          ? source
          : toValue(source))]

  return watch(source as WatchSource<T[]>, (newList, _, onCleanup) => {
    const oldListRemains = Array.from({ length: oldList.length })
    const added: T[] = []
    for (const obj of newList) {
      let found = false
      for (let i = 0; i < oldList.length; i++) {
        if (!oldListRemains[i] && obj === oldList[i]) {
          oldListRemains[i] = true
          found = true
          break
        }
      }
      if (!found)
        added.push(obj)
    }
    const removed = oldList.filter((_, i) => !oldListRemains[i])
    cb(newList, oldList, added, removed, onCleanup)
    oldList = [...newList]
  }, options)
}

Type Aliases

WatchArrayCallback<V = any, OV = any>

type WatchArrayCallback<V = any, OV = any> = (value: V, oldValue: OV, added: V, removed: OV, onCleanup: (cleanupFn: () => void) => void) => any;

Generated by Syntax Scribe