vue3-core/packages/runtime-core/src/apiWatch.ts

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

506 lines
13 KiB
TypeScript
Raw Normal View History

2019-05-29 23:44:59 +08:00
import {
type ComputedRef,
type DebuggerOptions,
2021-07-10 09:47:15 +08:00
type EffectScheduler,
ReactiveEffect,
ReactiveFlags,
2021-07-10 09:47:15 +08:00
type Ref,
getCurrentScope,
isReactive,
isRef,
2022-01-18 09:17:22 +08:00
isShallow,
} from '@vue/reactivity'
import { type SchedulerJob, queueJob } from './scheduler'
import {
EMPTY_OBJ,
NOOP,
extend,
hasChanged,
isArray,
isFunction,
isMap,
isObject,
2023-02-03 09:54:15 +08:00
isPlainObject,
isSet,
isString,
remove,
} from '@vue/shared'
import {
2019-09-07 00:58:31 +08:00
type ComponentInternalInstance,
currentInstance,
isInSSRComponentSetup,
setCurrentInstance,
} from './component'
import {
2019-09-07 00:58:31 +08:00
ErrorCodes,
callWithAsyncErrorHandling,
callWithErrorHandling,
} from './errorHandling'
2019-11-03 00:18:35 +08:00
import { queuePostRenderEffect } from './renderer'
import { warn } from './warning'
import { DeprecationTypes } from './compat/compatConfig'
2021-04-10 11:51:50 +08:00
import { checkCompatEnabled, isCompatEnabled } from './compat/compatConfig'
2021-04-22 21:49:25 +08:00
import type { ObjectWatchOptionItem } from './componentOptions'
import { useSSRContext } from './helpers/useSsrContext'
2019-10-22 23:26:48 +08:00
export type WatchEffect = (onCleanup: OnCleanup) => void
2019-12-31 00:30:12 +08:00
export type WatchSource<T = any> = Ref<T> | ComputedRef<T> | (() => T)
export type WatchCallback<V = any, OV = any> = (
value: V,
oldValue: OV,
onCleanup: OnCleanup,
2019-10-22 23:26:48 +08:00
) => any
2019-05-29 23:44:59 +08:00
type MapSources<T, Immediate> = {
[K in keyof T]: T[K] extends WatchSource<infer V>
2021-07-20 06:24:18 +08:00
? Immediate extends true
? V | undefined
: V
: T[K] extends object
? Immediate extends true
? T[K] | undefined
: T[K]
: never
}
type OnCleanup = (cleanupFn: () => void) => void
2019-12-31 00:30:12 +08:00
2021-07-10 09:47:15 +08:00
export interface WatchOptionsBase extends DebuggerOptions {
2019-05-29 23:44:59 +08:00
flush?: 'pre' | 'post' | 'sync'
}
export interface WatchOptions<Immediate = boolean> extends WatchOptionsBase {
immediate?: Immediate
deep?: boolean
once?: boolean
}
export type WatchStopHandle = () => void
2019-08-19 10:49:08 +08:00
// Simple effect.
export function watchEffect(
effect: WatchEffect,
options?: WatchOptionsBase,
): WatchStopHandle {
return doWatch(effect, null, options)
}
2021-07-10 09:47:15 +08:00
export function watchPostEffect(
effect: WatchEffect,
options?: DebuggerOptions,
) {
2021-07-20 06:24:18 +08:00
return doWatch(
effect,
null,
2023-02-03 09:54:15 +08:00
__DEV__ ? extend({}, options as any, { flush: 'post' }) : { flush: 'post' },
2021-07-20 06:24:18 +08:00
)
2021-07-10 09:47:15 +08:00
}
2021-07-21 04:49:54 +08:00
export function watchSyncEffect(
effect: WatchEffect,
options?: DebuggerOptions,
) {
return doWatch(
effect,
null,
2023-02-03 09:54:15 +08:00
__DEV__ ? extend({}, options as any, { flush: 'sync' }) : { flush: 'sync' },
2021-07-21 04:49:54 +08:00
)
}
// initial value for watchers to trigger on undefined initial values
const INITIAL_WATCHER_VALUE = {}
type MultiWatchSources = (WatchSource<unknown> | object)[]
// overload: single source + cb
export function watch<T, Immediate extends Readonly<boolean> = false>(
source: WatchSource<T>,
cb: WatchCallback<T, Immediate extends true ? T | undefined : T>,
options?: WatchOptions<Immediate>,
): WatchStopHandle
// overload: array of multiple sources + cb
export function watch<
T extends MultiWatchSources,
Immediate extends Readonly<boolean> = false,
>(
sources: [...T],
cb: WatchCallback<MapSources<T, false>, MapSources<T, Immediate>>,
options?: WatchOptions<Immediate>,
): WatchStopHandle
// overload: multiple sources w/ `as const`
// watch([foo, bar] as const, () => {})
// somehow [...T] breaks when the type is readonly
export function watch<
T extends Readonly<MultiWatchSources>,
Immediate extends Readonly<boolean> = false,
>(
source: T,
cb: WatchCallback<MapSources<T, false>, MapSources<T, Immediate>>,
options?: WatchOptions<Immediate>,
): WatchStopHandle
2019-08-19 10:49:08 +08:00
// overload: watching reactive object w/ cb
export function watch<
T extends object,
Immediate extends Readonly<boolean> = false,
>(
source: T,
2021-07-20 06:24:18 +08:00
cb: WatchCallback<T, Immediate extends true ? T | undefined : T>,
options?: WatchOptions<Immediate>,
): WatchStopHandle
2019-08-19 10:49:08 +08:00
// implementation
export function watch<T = any, Immediate extends Readonly<boolean> = false>(
source: T | WatchSource<T>,
cb: any,
options?: WatchOptions<Immediate>,
): WatchStopHandle {
if (__DEV__ && !isFunction(cb)) {
warn(
`\`watch(fn, options?)\` signature has been moved to a separate API. ` +
`Use \`watchEffect(fn, options?)\` instead. \`watch\` now only ` +
`supports \`watch(source, cb, options?) signature.`,
)
2019-08-19 10:49:08 +08:00
}
return doWatch(source as any, cb, options)
2019-08-19 10:49:08 +08:00
}
function doWatch(
source: WatchSource | WatchSource[] | WatchEffect | object,
2019-12-31 00:30:12 +08:00
cb: WatchCallback | null,
{
immediate,
deep,
flush,
once,
onTrack,
onTrigger,
}: WatchOptions = EMPTY_OBJ,
): WatchStopHandle {
if (cb && once) {
const _cb = cb
cb = (...args) => {
_cb(...args)
unwatch()
}
}
// TODO remove in 3.5
if (__DEV__ && deep !== void 0 && typeof deep === 'number') {
warn(
`watch() "deep" option with number value will be used as watch depth in future versions. ` +
`Please use a boolean instead to avoid potential breakage.`,
)
}
if (__DEV__ && !cb) {
if (immediate !== undefined) {
warn(
`watch() "immediate" option is only respected when using the ` +
`watch(source, callback, options?) signature.`,
)
}
if (deep !== undefined) {
warn(
`watch() "deep" option is only respected when using the ` +
`watch(source, callback, options?) signature.`,
)
}
if (once !== undefined) {
warn(
`watch() "once" option is only respected when using the ` +
`watch(source, callback, options?) signature.`,
)
}
}
const warnInvalidSource = (s: unknown) => {
warn(
`Invalid watch source: `,
s,
`A watch source can only be a getter/effect function, a ref, ` +
`a reactive object, or an array of these types.`,
)
}
const instance = currentInstance
const reactiveGetter = (source: object) =>
deep === true
? source // traverse will happen in wrapped getter below
: // for deep: false, only traverse root-level properties
traverse(source, deep === false ? 1 : undefined)
let getter: () => any
let forceTrigger = false
let isMultiSource = false
if (isRef(source)) {
2021-06-27 09:35:25 +08:00
getter = () => source.value
2022-01-18 09:17:22 +08:00
forceTrigger = isShallow(source)
} else if (isReactive(source)) {
getter = () => reactiveGetter(source)
forceTrigger = true
} else if (isArray(source)) {
isMultiSource = true
forceTrigger = source.some(s => isReactive(s) || isShallow(s))
getter = () =>
source.map(s => {
if (isRef(s)) {
return s.value
} else if (isReactive(s)) {
return reactiveGetter(s)
} else if (isFunction(s)) {
return callWithErrorHandling(s, instance, ErrorCodes.WATCH_GETTER)
} else {
__DEV__ && warnInvalidSource(s)
}
})
} else if (isFunction(source)) {
if (cb) {
// getter with cb
getter = () =>
callWithErrorHandling(source, instance, ErrorCodes.WATCH_GETTER)
} else {
// no cb -> simple effect
getter = () => {
if (cleanup) {
cleanup()
}
return callWithAsyncErrorHandling(
source,
instance,
ErrorCodes.WATCH_CALLBACK,
[onCleanup],
)
}
}
} else {
getter = NOOP
__DEV__ && warnInvalidSource(source)
}
2021-04-08 00:24:45 +08:00
// 2.x array mutation watch compat
if (__COMPAT__ && cb && !deep) {
const baseGetter = getter
getter = () => {
const val = baseGetter()
if (
isArray(val) &&
2021-04-10 11:51:50 +08:00
checkCompatEnabled(DeprecationTypes.WATCH_ARRAY, instance)
) {
traverse(val)
2021-04-08 00:24:45 +08:00
}
return val
}
}
if (cb && deep) {
const baseGetter = getter
getter = () => traverse(baseGetter())
}
let cleanup: (() => void) | undefined
let onCleanup: OnCleanup = (fn: () => void) => {
cleanup = effect.onStop = () => {
2019-09-07 00:58:31 +08:00
callWithErrorHandling(fn, instance, ErrorCodes.WATCH_CLEANUP)
cleanup = effect.onStop = undefined
}
2019-06-06 15:19:04 +08:00
}
// in SSR there is no need to setup an actual effect, and it should be noop
// unless it's eager or sync flush
let ssrCleanup: (() => void)[] | undefined
if (__SSR__ && isInSSRComponentSetup) {
// we will also not call the invalidate callback (+ runner is not set up)
onCleanup = NOOP
if (!cb) {
getter()
} else if (immediate) {
callWithAsyncErrorHandling(cb, instance, ErrorCodes.WATCH_CALLBACK, [
getter(),
isMultiSource ? [] : undefined,
onCleanup,
])
}
if (flush === 'sync') {
const ctx = useSSRContext()!
ssrCleanup = ctx.__watcherHandles || (ctx.__watcherHandles = [])
} else {
return NOOP
}
}
let oldValue: any = isMultiSource
? new Array((source as []).length).fill(INITIAL_WATCHER_VALUE)
: INITIAL_WATCHER_VALUE
const job: SchedulerJob = () => {
if (!effect.active || !effect.dirty) {
return
}
if (cb) {
// watch(source, cb)
const newValue = effect.run()
2021-04-08 00:24:45 +08:00
if (
deep ||
forceTrigger ||
(isMultiSource
? (newValue as any[]).some((v, i) => hasChanged(v, oldValue[i]))
: hasChanged(newValue, oldValue)) ||
2021-04-08 00:24:45 +08:00
(__COMPAT__ &&
isArray(newValue) &&
2021-04-10 11:21:13 +08:00
isCompatEnabled(DeprecationTypes.WATCH_ARRAY, instance))
2021-04-08 00:24:45 +08:00
) {
// cleanup before running cb again
if (cleanup) {
cleanup()
2019-05-29 23:44:59 +08:00
}
callWithAsyncErrorHandling(cb, instance, ErrorCodes.WATCH_CALLBACK, [
newValue,
// pass undefined as the old value when it's changed for the first time
2023-01-12 19:58:11 +08:00
oldValue === INITIAL_WATCHER_VALUE
? undefined
2023-01-12 19:58:11 +08:00
: isMultiSource && oldValue[0] === INITIAL_WATCHER_VALUE
? []
: oldValue,
onCleanup,
])
oldValue = newValue
2019-05-29 23:44:59 +08:00
}
} else {
// watchEffect
effect.run()
}
}
2019-05-29 23:44:59 +08:00
// important: mark the job as a watcher callback so that scheduler knows
// it is allowed to self-trigger (#1727)
job.allowRecurse = !!cb
let scheduler: EffectScheduler
if (flush === 'sync') {
2021-05-28 08:58:27 +08:00
scheduler = job as any // the scheduler function gets called directly
} else if (flush === 'post') {
scheduler = () => queuePostRenderEffect(job, instance && instance.suspense)
} else {
// default: 'pre'
job.pre = true
if (instance) job.id = instance.uid
scheduler = () => queueJob(job)
}
2019-08-20 02:44:52 +08:00
const effect = new ReactiveEffect(getter, NOOP, scheduler)
2019-05-29 23:44:59 +08:00
const scope = getCurrentScope()
const unwatch = () => {
effect.stop()
if (scope) {
remove(scope.effects, effect)
}
}
if (__DEV__) {
effect.onTrack = onTrack
effect.onTrigger = onTrigger
}
// initial run
if (cb) {
if (immediate) {
job()
2019-08-20 02:44:52 +08:00
} else {
oldValue = effect.run()
2019-08-20 02:44:52 +08:00
}
} else if (flush === 'post') {
queuePostRenderEffect(
effect.run.bind(effect),
instance && instance.suspense,
)
} else {
effect.run()
2019-05-29 23:44:59 +08:00
}
if (__SSR__ && ssrCleanup) ssrCleanup.push(unwatch)
return unwatch
2019-05-29 23:44:59 +08:00
}
2019-09-04 23:36:27 +08:00
// this.$watch
export function instanceWatch(
2019-09-07 00:58:31 +08:00
this: ComponentInternalInstance,
2019-09-04 23:36:27 +08:00
source: string | Function,
2021-04-22 21:49:25 +08:00
value: WatchCallback | ObjectWatchOptionItem,
2019-09-04 23:36:27 +08:00
options?: WatchOptions,
): WatchStopHandle {
const publicThis = this.proxy as any
const getter = isString(source)
? source.includes('.')
? createPathGetter(publicThis, source)
: () => publicThis[source]
: source.bind(publicThis, publicThis)
2021-04-22 21:49:25 +08:00
let cb
if (isFunction(value)) {
cb = value
} else {
cb = value.handler as Function
options = value
}
const reset = setCurrentInstance(this)
const res = doWatch(getter, cb.bind(publicThis), options)
reset()
return res
2019-09-04 23:36:27 +08:00
}
export function createPathGetter(ctx: any, path: string) {
const segments = path.split('.')
return () => {
let cur = ctx
for (let i = 0; i < segments.length && cur; i++) {
cur = cur[segments[i]]
}
return cur
}
}
export function traverse(
value: unknown,
depth?: number,
currentDepth = 0,
seen?: Set<unknown>,
) {
if (!isObject(value) || (value as any)[ReactiveFlags.SKIP]) {
return value
}
if (depth && depth > 0) {
if (currentDepth >= depth) {
return value
}
currentDepth++
}
seen = seen || new Set()
if (seen.has(value)) {
return value
}
2019-05-29 23:44:59 +08:00
seen.add(value)
if (isRef(value)) {
traverse(value.value, depth, currentDepth, seen)
} else if (isArray(value)) {
2019-05-29 23:44:59 +08:00
for (let i = 0; i < value.length; i++) {
traverse(value[i], depth, currentDepth, seen)
2019-05-29 23:44:59 +08:00
}
} else if (isSet(value) || isMap(value)) {
value.forEach((v: any) => {
traverse(v, depth, currentDepth, seen)
2019-05-29 23:44:59 +08:00
})
} else if (isPlainObject(value)) {
2019-05-29 23:44:59 +08:00
for (const key in value) {
traverse(value[key], depth, currentDepth, seen)
2019-05-29 23:44:59 +08:00
}
}
return value
}