apiWatch.ts 7.7 KB

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