Vue3$SideEffect-Watcher

94 阅读1分钟

Vue3$SideEffect-Watcher

Vue 是数据驱动页面。改变数据最直接的方式是事件或者生命周期钩子。另一些情况,我们需要在数据改变的时候改变另一些数据。常见的例子是带回显的具有联动的表单。

0. API

watch(
	sources: WatchSource,
	cb: (newValue: T, oldValue: T, cleanup: (func) => void)) => any,
	options?: WatchOptions
): WatchStopHandle

1. Watch Source Types

根据监视的对象 / 属性不同,watch 的数据源可以分为:

  1. ref(包括计算属性)
    • 基本类型: 正常
    • 对象类型: 只监视对象地址 ==> use { deep: true } to watch all properties
  2. reactive:默认开启了深度监视 (默认1/2)
  3. ref / reactive properties:
    • 基本类型:getter函数
    • 对象类型:
      • 本身:只能监视其属性 // 不建议 (默认2/2)
      • getter:只能监视对象地址 ==> use { deep: true }
  4. Array:元素的类型是上面的
newValue & oldValue:
- primitive type: !=
- object type:
	- if change the object reference: !=
	- if change object's property: == (the same object)

2. Watcher Options

watcher options:

  • deep:对于监视属性(对象类型的),加上后才能监视属性的属性变化
  • immediate
  • once

3. Callback Flush Timing

By default, a watcher's callback is called after parent component updates, and before the owner component's DOM updates.(我有些没看明白)

post watchers:
如果想要在 DOM 更新后触发 watch / watchEffect:
- watch: 第三个参数: { flush: 'post' }
- watchEffect: 第二个参数: { flush: 'post' }
- watchEffect 变体: watchPostEffect
sync watchers: { flush: 'sync' }
watchSyncEffect

4. Stopping a watcher

// 异步创建的watcher, 需要手动停止
const unwatch = watchEffect(() => {})
unwatch()

5. watchEffect()

不需要指定源。

watchEffect() allows us to track the callback's reactive dependencies automatically. only tracks dependencies during its synchronous execution. When using it with an async callback, only properties accessed before the first await tick will be tracked.

Links

VueWatchers