apiWatch.ts 7.2 KB

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