Skip to content

Commit

Permalink
feat: watchPostEffect
Browse files Browse the repository at this point in the history
  • Loading branch information
yyx990803 committed Jul 16, 2021
1 parent 3b64508 commit 42ace95
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 5 deletions.
27 changes: 27 additions & 0 deletions packages/runtime-core/__tests__/apiWatch.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import {
shallowRef,
Ref
} from '@vue/reactivity'
import { watchPostEffect } from '../src/apiWatch'

// reference: https://vue-composition-api-rfc.netlify.com/api.html#watch

Expand Down Expand Up @@ -363,6 +364,32 @@ describe('api: watch', () => {
expect(result).toBe(true)
})

it('watchPostEffect', async () => {
const count = ref(0)
let result
const assertion = jest.fn(count => {
result = serializeInner(root) === `${count}`
})

const Comp = {
setup() {
watchPostEffect(() => {
assertion(count.value)
})
return () => count.value
}
}
const root = nodeOps.createElement('div')
render(h(Comp), root)
expect(assertion).toHaveBeenCalledTimes(1)
expect(result).toBe(true)

count.value++
await nextTick()
expect(assertion).toHaveBeenCalledTimes(2)
expect(result).toBe(true)
})

it('flush timing: sync', async () => {
const count = ref(0)
const count2 = ref(0)
Expand Down
17 changes: 12 additions & 5 deletions packages/runtime-core/src/apiWatch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@ import {
Ref,
ComputedRef,
ReactiveEffect,
ReactiveEffectOptions,
isReactive,
ReactiveFlags,
EffectScheduler
EffectScheduler,
DebuggerOptions
} from '@vue/reactivity'
import { SchedulerJob, queuePreFlushCb } from './scheduler'
import {
Expand Down Expand Up @@ -58,10 +58,8 @@ type MapSources<T, Immediate> = {

type InvalidateCbRegistrator = (cb: () => void) => void

export interface WatchOptionsBase {
export interface WatchOptionsBase extends DebuggerOptions {
flush?: 'pre' | 'post' | 'sync'
onTrack?: ReactiveEffectOptions['onTrack']
onTrigger?: ReactiveEffectOptions['onTrigger']
}

export interface WatchOptions<Immediate = boolean> extends WatchOptionsBase {
Expand All @@ -79,6 +77,15 @@ export function watchEffect(
return doWatch(effect, null, options)
}

export function watchPostEffect(
effect: WatchEffect,
options?: DebuggerOptions
) {
return doWatch(effect, null, (__DEV__
? Object.assign(options || {}, { flush: 'post' })
: { flush: 'post' }) as WatchOptionsBase)
}

// initial value for watchers to trigger on undefined initial values
const INITIAL_WATCHER_VALUE = {}

Expand Down

0 comments on commit 42ace95

Please sign in to comment.