apiWatch.ts 12 KB

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