apiWatch.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. import {
  2. isRef,
  3. isShallow,
  4. Ref,
  5. ComputedRef,
  6. ReactiveEffect,
  7. isReactive,
  8. ReactiveFlags,
  9. EffectScheduler,
  10. DebuggerOptions,
  11. getCurrentScope
  12. } from '@vue/reactivity'
  13. import { SchedulerJob, queueJob } from './scheduler'
  14. import {
  15. EMPTY_OBJ,
  16. isObject,
  17. isArray,
  18. isFunction,
  19. isString,
  20. hasChanged,
  21. NOOP,
  22. remove,
  23. isMap,
  24. isSet,
  25. isPlainObject,
  26. extend
  27. } from '@vue/shared'
  28. import {
  29. currentInstance,
  30. ComponentInternalInstance,
  31. isInSSRComponentSetup,
  32. setCurrentInstance,
  33. unsetCurrentInstance
  34. } from './component'
  35. import {
  36. ErrorCodes,
  37. callWithErrorHandling,
  38. callWithAsyncErrorHandling
  39. } from './errorHandling'
  40. import { queuePostRenderEffect } from './renderer'
  41. import { warn } from './warning'
  42. import { DeprecationTypes } from './compat/compatConfig'
  43. import { checkCompatEnabled, isCompatEnabled } from './compat/compatConfig'
  44. import { ObjectWatchOptionItem } from './componentOptions'
  45. import { useSSRContext } from '@vue/runtime-core'
  46. import { SSRContext } from '@vue/server-renderer'
  47. export type WatchEffect = (onCleanup: OnCleanup) => void
  48. export type WatchSource<T = any> = Ref<T> | ComputedRef<T> | (() => T)
  49. export type WatchCallback<V = any, OV = any> = (
  50. value: V,
  51. oldValue: OV,
  52. onCleanup: OnCleanup
  53. ) => any
  54. type MapSources<T, Immediate> = {
  55. [K in keyof T]: T[K] extends WatchSource<infer V>
  56. ? Immediate extends true
  57. ? V | undefined
  58. : V
  59. : T[K] extends object
  60. ? Immediate extends true
  61. ? T[K] | undefined
  62. : T[K]
  63. : never
  64. }
  65. type OnCleanup = (cleanupFn: () => void) => void
  66. export interface WatchOptionsBase extends DebuggerOptions {
  67. flush?: 'pre' | 'post' | 'sync'
  68. }
  69. export interface WatchOptions<Immediate = boolean> extends WatchOptionsBase {
  70. immediate?: Immediate
  71. deep?: boolean
  72. }
  73. export type WatchStopHandle = () => void
  74. // Simple effect.
  75. export function watchEffect(
  76. effect: WatchEffect,
  77. options?: WatchOptionsBase
  78. ): WatchStopHandle {
  79. return doWatch(effect, null, options)
  80. }
  81. export function watchPostEffect(
  82. effect: WatchEffect,
  83. options?: DebuggerOptions
  84. ) {
  85. return doWatch(
  86. effect,
  87. null,
  88. __DEV__ ? extend({}, options as any, { flush: 'post' }) : { flush: 'post' }
  89. )
  90. }
  91. export function watchSyncEffect(
  92. effect: WatchEffect,
  93. options?: DebuggerOptions
  94. ) {
  95. return doWatch(
  96. effect,
  97. null,
  98. __DEV__ ? extend({}, options as any, { flush: 'sync' }) : { flush: 'sync' }
  99. )
  100. }
  101. // initial value for watchers to trigger on undefined initial values
  102. const INITIAL_WATCHER_VALUE = {}
  103. type MultiWatchSources = (WatchSource<unknown> | object)[]
  104. // overload: array of multiple sources + cb
  105. export function watch<
  106. T extends MultiWatchSources,
  107. Immediate extends Readonly<boolean> = false
  108. >(
  109. sources: [...T],
  110. cb: WatchCallback<MapSources<T, false>, MapSources<T, Immediate>>,
  111. options?: WatchOptions<Immediate>
  112. ): WatchStopHandle
  113. // overload: multiple sources w/ `as const`
  114. // watch([foo, bar] as const, () => {})
  115. // somehow [...T] breaks when the type is readonly
  116. export function watch<
  117. T extends Readonly<MultiWatchSources>,
  118. Immediate extends Readonly<boolean> = false
  119. >(
  120. source: T,
  121. cb: WatchCallback<MapSources<T, false>, MapSources<T, Immediate>>,
  122. options?: WatchOptions<Immediate>
  123. ): WatchStopHandle
  124. // overload: single source + cb
  125. export function watch<T, Immediate extends Readonly<boolean> = false>(
  126. source: WatchSource<T>,
  127. cb: WatchCallback<T, Immediate extends true ? T | undefined : T>,
  128. options?: WatchOptions<Immediate>
  129. ): WatchStopHandle
  130. // overload: watching reactive object w/ cb
  131. export function watch<
  132. T extends object,
  133. Immediate extends Readonly<boolean> = false
  134. >(
  135. source: T,
  136. cb: WatchCallback<T, Immediate extends true ? T | undefined : T>,
  137. options?: WatchOptions<Immediate>
  138. ): WatchStopHandle
  139. // implementation
  140. export function watch<T = any, Immediate extends Readonly<boolean> = false>(
  141. source: T | WatchSource<T>,
  142. cb: any,
  143. options?: WatchOptions<Immediate>
  144. ): WatchStopHandle {
  145. if (__DEV__ && !isFunction(cb)) {
  146. warn(
  147. `\`watch(fn, options?)\` signature has been moved to a separate API. ` +
  148. `Use \`watchEffect(fn, options?)\` instead. \`watch\` now only ` +
  149. `supports \`watch(source, cb, options?) signature.`
  150. )
  151. }
  152. return doWatch(source as any, cb, options)
  153. }
  154. function doWatch(
  155. source: WatchSource | WatchSource[] | WatchEffect | object,
  156. cb: WatchCallback | null,
  157. { immediate, deep, flush, onTrack, onTrigger }: WatchOptions = EMPTY_OBJ
  158. ): WatchStopHandle {
  159. if (__DEV__ && !cb) {
  160. if (immediate !== undefined) {
  161. warn(
  162. `watch() "immediate" option is only respected when using the ` +
  163. `watch(source, callback, options?) signature.`
  164. )
  165. }
  166. if (deep !== undefined) {
  167. warn(
  168. `watch() "deep" option is only respected when using the ` +
  169. `watch(source, callback, options?) signature.`
  170. )
  171. }
  172. }
  173. const warnInvalidSource = (s: unknown) => {
  174. warn(
  175. `Invalid watch source: `,
  176. s,
  177. `A watch source can only be a getter/effect function, a ref, ` +
  178. `a reactive object, or an array of these types.`
  179. )
  180. }
  181. const instance =
  182. getCurrentScope() === currentInstance?.scope ? currentInstance : null
  183. // const instance = currentInstance
  184. let getter: () => any
  185. let forceTrigger = false
  186. let isMultiSource = false
  187. if (isRef(source)) {
  188. getter = () => source.value
  189. forceTrigger = isShallow(source)
  190. } else if (isReactive(source)) {
  191. getter = () => source
  192. deep = true
  193. } else if (isArray(source)) {
  194. isMultiSource = true
  195. forceTrigger = source.some(s => isReactive(s) || isShallow(s))
  196. getter = () =>
  197. source.map(s => {
  198. if (isRef(s)) {
  199. return s.value
  200. } else if (isReactive(s)) {
  201. return traverse(s)
  202. } else if (isFunction(s)) {
  203. return callWithErrorHandling(s, instance, ErrorCodes.WATCH_GETTER)
  204. } else {
  205. __DEV__ && warnInvalidSource(s)
  206. }
  207. })
  208. } else if (isFunction(source)) {
  209. if (cb) {
  210. // getter with cb
  211. getter = () =>
  212. callWithErrorHandling(source, instance, ErrorCodes.WATCH_GETTER)
  213. } else {
  214. // no cb -> simple effect
  215. getter = () => {
  216. if (instance && instance.isUnmounted) {
  217. return
  218. }
  219. if (cleanup) {
  220. cleanup()
  221. }
  222. return callWithAsyncErrorHandling(
  223. source,
  224. instance,
  225. ErrorCodes.WATCH_CALLBACK,
  226. [onCleanup]
  227. )
  228. }
  229. }
  230. } else {
  231. getter = NOOP
  232. __DEV__ && warnInvalidSource(source)
  233. }
  234. // 2.x array mutation watch compat
  235. if (__COMPAT__ && cb && !deep) {
  236. const baseGetter = getter
  237. getter = () => {
  238. const val = baseGetter()
  239. if (
  240. isArray(val) &&
  241. checkCompatEnabled(DeprecationTypes.WATCH_ARRAY, instance)
  242. ) {
  243. traverse(val)
  244. }
  245. return val
  246. }
  247. }
  248. if (cb && deep) {
  249. const baseGetter = getter
  250. getter = () => traverse(baseGetter())
  251. }
  252. let cleanup: () => void
  253. let onCleanup: OnCleanup = (fn: () => void) => {
  254. cleanup = effect.onStop = () => {
  255. callWithErrorHandling(fn, instance, ErrorCodes.WATCH_CLEANUP)
  256. }
  257. }
  258. // in SSR there is no need to setup an actual effect, and it should be noop
  259. // unless it's eager or sync flush
  260. let ssrCleanup: (() => void)[] | undefined
  261. if (__SSR__ && isInSSRComponentSetup) {
  262. // we will also not call the invalidate callback (+ runner is not set up)
  263. onCleanup = NOOP
  264. if (!cb) {
  265. getter()
  266. } else if (immediate) {
  267. callWithAsyncErrorHandling(cb, instance, ErrorCodes.WATCH_CALLBACK, [
  268. getter(),
  269. isMultiSource ? [] : undefined,
  270. onCleanup
  271. ])
  272. }
  273. if (flush === 'sync') {
  274. const ctx = useSSRContext() as SSRContext
  275. ssrCleanup = ctx.__watcherHandles || (ctx.__watcherHandles = [])
  276. } else {
  277. return NOOP
  278. }
  279. }
  280. let oldValue: any = isMultiSource
  281. ? new Array((source as []).length).fill(INITIAL_WATCHER_VALUE)
  282. : INITIAL_WATCHER_VALUE
  283. const job: SchedulerJob = () => {
  284. if (!effect.active) {
  285. return
  286. }
  287. if (cb) {
  288. // watch(source, cb)
  289. const newValue = effect.run()
  290. if (
  291. deep ||
  292. forceTrigger ||
  293. (isMultiSource
  294. ? (newValue as any[]).some((v, i) =>
  295. hasChanged(v, (oldValue as any[])[i])
  296. )
  297. : hasChanged(newValue, oldValue)) ||
  298. (__COMPAT__ &&
  299. isArray(newValue) &&
  300. isCompatEnabled(DeprecationTypes.WATCH_ARRAY, instance))
  301. ) {
  302. // cleanup before running cb again
  303. if (cleanup) {
  304. cleanup()
  305. }
  306. callWithAsyncErrorHandling(cb, instance, ErrorCodes.WATCH_CALLBACK, [
  307. newValue,
  308. // pass undefined as the old value when it's changed for the first time
  309. oldValue === INITIAL_WATCHER_VALUE
  310. ? undefined
  311. : isMultiSource && oldValue[0] === INITIAL_WATCHER_VALUE
  312. ? []
  313. : oldValue,
  314. onCleanup
  315. ])
  316. oldValue = newValue
  317. }
  318. } else {
  319. // watchEffect
  320. effect.run()
  321. }
  322. }
  323. // important: mark the job as a watcher callback so that scheduler knows
  324. // it is allowed to self-trigger (#1727)
  325. job.allowRecurse = !!cb
  326. let scheduler: EffectScheduler
  327. if (flush === 'sync') {
  328. scheduler = job as any // the scheduler function gets called directly
  329. } else if (flush === 'post') {
  330. scheduler = () => queuePostRenderEffect(job, instance && instance.suspense)
  331. } else {
  332. // default: 'pre'
  333. job.pre = true
  334. if (instance) job.id = instance.uid
  335. scheduler = () => queueJob(job)
  336. }
  337. const effect = new ReactiveEffect(getter, scheduler)
  338. if (__DEV__) {
  339. effect.onTrack = onTrack
  340. effect.onTrigger = onTrigger
  341. }
  342. // initial run
  343. if (cb) {
  344. if (immediate) {
  345. job()
  346. } else {
  347. oldValue = effect.run()
  348. }
  349. } else if (flush === 'post') {
  350. queuePostRenderEffect(
  351. effect.run.bind(effect),
  352. instance && instance.suspense
  353. )
  354. } else {
  355. effect.run()
  356. }
  357. const unwatch = () => {
  358. effect.stop()
  359. if (instance && instance.scope) {
  360. remove(instance.scope.effects!, effect)
  361. }
  362. }
  363. if (__SSR__ && ssrCleanup) ssrCleanup.push(unwatch)
  364. return unwatch
  365. }
  366. // this.$watch
  367. export function instanceWatch(
  368. this: ComponentInternalInstance,
  369. source: string | Function,
  370. value: WatchCallback | ObjectWatchOptionItem,
  371. options?: WatchOptions
  372. ): WatchStopHandle {
  373. const publicThis = this.proxy as any
  374. const getter = isString(source)
  375. ? source.includes('.')
  376. ? createPathGetter(publicThis, source)
  377. : () => publicThis[source]
  378. : source.bind(publicThis, publicThis)
  379. let cb
  380. if (isFunction(value)) {
  381. cb = value
  382. } else {
  383. cb = value.handler as Function
  384. options = value
  385. }
  386. const cur = currentInstance
  387. setCurrentInstance(this)
  388. const res = doWatch(getter, cb.bind(publicThis), options)
  389. if (cur) {
  390. setCurrentInstance(cur)
  391. } else {
  392. unsetCurrentInstance()
  393. }
  394. return res
  395. }
  396. export function createPathGetter(ctx: any, path: string) {
  397. const segments = path.split('.')
  398. return () => {
  399. let cur = ctx
  400. for (let i = 0; i < segments.length && cur; i++) {
  401. cur = cur[segments[i]]
  402. }
  403. return cur
  404. }
  405. }
  406. export function traverse(value: unknown, seen?: Set<unknown>) {
  407. if (!isObject(value) || (value as any)[ReactiveFlags.SKIP]) {
  408. return value
  409. }
  410. seen = seen || new Set()
  411. if (seen.has(value)) {
  412. return value
  413. }
  414. seen.add(value)
  415. if (isRef(value)) {
  416. traverse(value.value, seen)
  417. } else if (isArray(value)) {
  418. for (let i = 0; i < value.length; i++) {
  419. traverse(value[i], seen)
  420. }
  421. } else if (isSet(value) || isMap(value)) {
  422. value.forEach((v: any) => {
  423. traverse(v, seen)
  424. })
  425. } else if (isPlainObject(value)) {
  426. for (const key in value) {
  427. traverse((value as any)[key], seen)
  428. }
  429. }
  430. return value
  431. }