响应式:监听器
watch()
监听响应式数据的变化。
类型定义
ts
// 监听 ref
declare function watch<T extends Ref>(
ref: T,
cb: WatchCallback<T['value']>,
options?: WatchOptions
): Watcher
// 监听 reactive 对象
declare function watch<T extends Reactive | ShallowReactive>(
target: T,
cb: WatchCallback<T[typeof RAW_VALUE]>,
options?: WatchOptions
): Watcher
// 监听多个源
declare function watch<T extends any[]>(
sources: T,
cb: WatchCallback<UnwarpSources<T>>,
options?: WatchOptions
): Watcher
// 监听 getter 函数
declare function watch<T>(getter: () => T, cb: WatchCallback<T>, options?: WatchOptions): Watcher参数
| 参数 | 类型 | 说明 |
|---|---|---|
source | WatchSource<T> | 数据源,可以是 ref、reactive 对象、getter 函数或数组 |
callback | WatchCallback<T> | 变化时的回调函数 |
options | WatchOptions | 可选配置 |
WatchCallback
ts
type WatchCallback<T> = (newValue: T, oldValue: T, onCleanup: WatcherOnCleanup) => voidWatchOptions
| 属性 | 类型 | 默认值 | 说明 |
|---|---|---|---|
immediate | boolean | false | 是否立即执行回调 |
deep | boolean | number | false | 是否深度监听 |
once | boolean | false | 是否只监听一次 |
flush | 'pre' | 'main' | 'post' | 'sync' | 'main' | 回调执行时机 |
scope | EffectScope | boolean | — | 指定作用域 |
返回值
| 类型 | 说明 |
|---|---|
Watcher | 监听器句柄,调用可停止监听 |
示例
监听 ref:
ts
import { ref, watch } from 'vitarx'
const count = ref(0)
watch(count, (newVal, oldVal) => {
console.log(`count 从 #123;oldVal} 变为 #123;newVal}`)
})监听 getter:
ts
watch(
() => state.count + state.step,
(sum) => console.log('sum:', sum)
)监听多个源:
ts
watch([firstName, lastName], ([first, last]) => {
console.log('全名:', first, last)
})清理副作用:
ts
watch(id, (newId, oldId, onCleanup) => {
const controller = new AbortController()
fetch(`/api/#123;newId}`, { signal: controller.signal })
.then((res) => res.json())
.then((data) => {
/* ... */
})
onCleanup(() => controller.abort())
})参考:watch 详解
watchEffect()
立即运行一个函数,并响应式地追踪其依赖。
类型定义
ts
declare function watchEffect(
effect: (onCleanup: WatcherOnCleanup) => void,
options?: WatcherOptions
): EffectWatcher参数
| 参数 | 类型 | 说明 |
|---|---|---|
effect | (onCleanup: WatcherOnCleanup) => void | 副作用函数 |
options | WatcherOptions | 可选配置 |
返回值
| 类型 | 说明 |
|---|---|
EffectWatcher | 监听器句柄,可用于停止监听 |
示例
ts
import { ref, watchEffect } from 'vitarx'
const count = ref(0)
watchEffect(() => {
console.log(`count 变化了: #123;count.value}`)
})watchPostEffect()
watchEffect() 的变体,在 DOM 更新后执行。
类型定义
ts
declare function watchPostEffect(
effect: (onCleanup: WatcherOnCleanup) => void,
options?: Omit<WatcherOptions, 'flush'>
): EffectWatcher详情
等同于 watchEffect(effect, { flush: 'post' }),在 DOM 更新完成后执行回调。
watchSyncEffect()
watchEffect() 的同步版本,在依赖变化时立即同步执行。
类型定义
ts
declare function watchSyncEffect(
effect: (onCleanup: WatcherOnCleanup) => void,
options?: Omit<WatcherOptions, 'flush'>
): EffectWatcher详情
等同于 watchEffect(effect, { flush: 'sync' }),在依赖变化时立即同步执行。
WARNING
同步执行可能导致性能问题,谨慎使用。