apiWatch.ts 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. import {
  2. effect,
  3. stop,
  4. isRef,
  5. Ref,
  6. ComputedRef,
  7. ReactiveEffectOptions
  8. } from '@vue/reactivity'
  9. import { queueJob } from './scheduler'
  10. import {
  11. EMPTY_OBJ,
  12. isObject,
  13. isArray,
  14. isFunction,
  15. isString,
  16. hasChanged
  17. } from '@vue/shared'
  18. import { recordEffect } from './apiReactivity'
  19. import {
  20. currentInstance,
  21. ComponentInternalInstance,
  22. currentSuspense,
  23. Data
  24. } from './component'
  25. import {
  26. ErrorCodes,
  27. callWithErrorHandling,
  28. callWithAsyncErrorHandling
  29. } from './errorHandling'
  30. import { onBeforeUnmount } from './apiLifecycle'
  31. import { queuePostRenderEffect } from './renderer'
  32. export type WatchHandler<T = any> = (
  33. value: T,
  34. oldValue: T,
  35. onCleanup: CleanupRegistrator
  36. ) => any
  37. export interface WatchOptions {
  38. lazy?: boolean
  39. flush?: 'pre' | 'post' | 'sync'
  40. deep?: boolean
  41. onTrack?: ReactiveEffectOptions['onTrack']
  42. onTrigger?: ReactiveEffectOptions['onTrigger']
  43. }
  44. type StopHandle = () => void
  45. type WatcherSource<T = any> = Ref<T> | ComputedRef<T> | (() => T)
  46. type MapSources<T> = {
  47. [K in keyof T]: T[K] extends WatcherSource<infer V> ? V : never
  48. }
  49. export type CleanupRegistrator = (invalidate: () => void) => void
  50. type SimpleEffect = (onCleanup: CleanupRegistrator) => void
  51. const invoke = (fn: Function) => fn()
  52. // overload #1: simple effect
  53. export function watch(effect: SimpleEffect, options?: WatchOptions): StopHandle
  54. // overload #2: single source + cb
  55. export function watch<T>(
  56. source: WatcherSource<T>,
  57. cb: WatchHandler<T>,
  58. options?: WatchOptions
  59. ): StopHandle
  60. // overload #3: array of multiple sources + cb
  61. // Readonly constraint helps the callback to correctly infer value types based
  62. // on position in the source array. Otherwise the values will get a union type
  63. // of all possible value types.
  64. export function watch<T extends Readonly<WatcherSource<unknown>[]>>(
  65. sources: T,
  66. cb: WatchHandler<MapSources<T>>,
  67. options?: WatchOptions
  68. ): StopHandle
  69. // implementation
  70. export function watch<T = any>(
  71. effectOrSource: WatcherSource<T> | WatcherSource<T>[] | SimpleEffect,
  72. cbOrOptions?: WatchHandler<T> | WatchOptions,
  73. options?: WatchOptions
  74. ): StopHandle {
  75. if (isFunction(cbOrOptions)) {
  76. // effect callback as 2nd argument - this is a source watcher
  77. return doWatch(effectOrSource, cbOrOptions, options)
  78. } else {
  79. // 2nd argument is either missing or an options object
  80. // - this is a simple effect watcher
  81. return doWatch(effectOrSource, null, cbOrOptions)
  82. }
  83. }
  84. function doWatch(
  85. source: WatcherSource | WatcherSource[] | SimpleEffect,
  86. cb: WatchHandler | null,
  87. { lazy, deep, flush, onTrack, onTrigger }: WatchOptions = EMPTY_OBJ
  88. ): StopHandle {
  89. const instance = currentInstance
  90. const suspense = currentSuspense
  91. let getter: () => any
  92. if (isArray(source)) {
  93. getter = () =>
  94. source.map(
  95. s =>
  96. isRef(s)
  97. ? s.value
  98. : callWithErrorHandling(s, instance, ErrorCodes.WATCH_GETTER)
  99. )
  100. } else if (isRef(source)) {
  101. getter = () => source.value
  102. } else if (cb) {
  103. // getter with cb
  104. getter = () =>
  105. callWithErrorHandling(source, instance, ErrorCodes.WATCH_GETTER)
  106. } else {
  107. // no cb -> simple effect
  108. getter = () => {
  109. if (instance && instance.isUnmounted) {
  110. return
  111. }
  112. if (cleanup) {
  113. cleanup()
  114. }
  115. return callWithErrorHandling(
  116. source,
  117. instance,
  118. ErrorCodes.WATCH_CALLBACK,
  119. [registerCleanup]
  120. )
  121. }
  122. }
  123. if (deep) {
  124. const baseGetter = getter
  125. getter = () => traverse(baseGetter())
  126. }
  127. let cleanup: Function
  128. const registerCleanup: CleanupRegistrator = (fn: () => void) => {
  129. cleanup = runner.options.onStop = () => {
  130. callWithErrorHandling(fn, instance, ErrorCodes.WATCH_CLEANUP)
  131. }
  132. }
  133. let oldValue = isArray(source) ? [] : undefined
  134. const applyCb = cb
  135. ? () => {
  136. if (instance && instance.isUnmounted) {
  137. return
  138. }
  139. const newValue = runner()
  140. if (deep || hasChanged(newValue, oldValue)) {
  141. // cleanup before running cb again
  142. if (cleanup) {
  143. cleanup()
  144. }
  145. callWithAsyncErrorHandling(cb, instance, ErrorCodes.WATCH_CALLBACK, [
  146. newValue,
  147. oldValue,
  148. registerCleanup
  149. ])
  150. oldValue = newValue
  151. }
  152. }
  153. : void 0
  154. let scheduler: (job: () => any) => void
  155. if (flush === 'sync') {
  156. scheduler = invoke
  157. } else if (flush === 'pre') {
  158. scheduler = job => {
  159. if (!instance || instance.vnode.el != null) {
  160. queueJob(job)
  161. } else {
  162. // with 'pre' option, the first call must happen before
  163. // the component is mounted so it is called synchronously.
  164. job()
  165. }
  166. }
  167. } else {
  168. scheduler = job => {
  169. queuePostRenderEffect(job, suspense)
  170. }
  171. }
  172. const runner = effect(getter, {
  173. lazy: true,
  174. // so it runs before component update effects in pre flush mode
  175. computed: true,
  176. onTrack,
  177. onTrigger,
  178. scheduler: applyCb ? () => scheduler(applyCb) : scheduler
  179. })
  180. if (!lazy) {
  181. if (applyCb) {
  182. scheduler(applyCb)
  183. } else {
  184. scheduler(runner)
  185. }
  186. } else {
  187. oldValue = runner()
  188. }
  189. recordEffect(runner)
  190. return () => {
  191. stop(runner)
  192. }
  193. }
  194. // this.$watch
  195. export function instanceWatch(
  196. this: ComponentInternalInstance,
  197. source: string | Function,
  198. cb: Function,
  199. options?: WatchOptions
  200. ): StopHandle {
  201. const ctx = this.renderProxy as Data
  202. const getter = isString(source) ? () => ctx[source] : source.bind(ctx)
  203. const stop = watch(getter, cb.bind(ctx), options)
  204. onBeforeUnmount(stop, this)
  205. return stop
  206. }
  207. function traverse(value: unknown, seen: Set<unknown> = new Set()) {
  208. if (!isObject(value) || seen.has(value)) {
  209. return
  210. }
  211. seen.add(value)
  212. if (isArray(value)) {
  213. for (let i = 0; i < value.length; i++) {
  214. traverse(value[i], seen)
  215. }
  216. } else if (value instanceof Map) {
  217. value.forEach((v, key) => {
  218. // to register mutation dep for existing keys
  219. traverse(value.get(key), seen)
  220. })
  221. } else if (value instanceof Set) {
  222. value.forEach(v => {
  223. traverse(v, seen)
  224. })
  225. } else {
  226. for (const key in value) {
  227. traverse(value[key], seen)
  228. }
  229. }
  230. return value
  231. }