/scope

The auto effect collecting for @vue/reactivity

Primary LanguageTypeScriptMIT LicenseMIT

The auto effect collecting for @vue/reactivity

npm npm bundle size

✳️ DEPRECATED: @vue/reactivity now ships effectScope builtin

Install

npm i @vue-reactivity/scope

Usage

Note: effectScope do NOT have equivalent in Vue. This package is designed to be used on non-Vue environment.

🥵 Collect and dispose manually

import { ref, computed, stop } from '@vue/reactivity'
import { watch, watchEffect } from '@vue-reactivity/watch'

const counter = ref(0)
let disposables = []

const doubled = computed(() => counter.value * 2)

const stopWatch = watch(doubled, () => console.log(double.value))

const stopWatchEffect = watchEffect(() => console.log('Count: ', double.value))

// manually collect effects
disposables.push(() => stop(doubled.effect))
disposables.push(stopWatch)
disposables.push(stopWatchEffect)

// to dispose all
disposables.forEach(d => d())
disposables = []

😎 With @vue-reactivity/scope

import { effectScope, ref, computed, watch, watchEffect, stop } from '@vue-reactivity/scope'

const counter = ref(0)

const scope = effectScope(() => {
  // computed, watch, watchEffect, effect ran inside the scope will be auto collected
  const doubled = computed(() => counter.value * 2)

  watch(doubled, () => console.log(double.value))

  watchEffect(() => console.log('Count: ', double.value))
})

// to dispose all effects
stop(scope)

This package redirects the APIs in @vue/reactivity and add some hook to them. You should always import APIs from @vue-reactivity/scope instead of @vue/reactivity.

License

MIT