Skip to content

Commit

Permalink
feature(apiWatch): 实现watchEffect函数
Browse files Browse the repository at this point in the history
  • Loading branch information
choukui committed Jun 15, 2022
1 parent 74f2b17 commit d04e878
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 7 deletions.
6 changes: 3 additions & 3 deletions src/runtime-core/__test__/apiWatch.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {
watch,
// watchEffect,
watchEffect,
// reactive,
// computed,
// nextTick,
Expand Down Expand Up @@ -38,7 +38,7 @@ import { ref } from "../../reactive";
// reference: https://vue-composition-api-rfc.netlify.com/api.html#watch

describe('api: watch', () => {
/*it('effect', async () => {
it('effect', async () => {
const state = reactive({ count: 0 })
let dummy
watchEffect(() => {
Expand All @@ -49,7 +49,7 @@ describe('api: watch', () => {
state.count++
await nextTick()
expect(dummy).toBe(1)
})*/
})

it('watching single source: getter', async () => {
const state = reactive({ count: 0 })
Expand Down
20 changes: 16 additions & 4 deletions src/runtime-core/apiWatch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,11 @@ type MapSources<T, Immediate> = {
type MultiWatchSources = (WatchSource<unknown> | object)[]
/********** TS类型声明 end ***********/

// watchEffect 实现,和watch的区别是:没有callback函数
export function watchEffect(effect: WatchEffect, options?: WatchOptionsBase) {
doWatch(effect, null, options)
}

// overload: single source + cb
export function watch<T, Immediate extends Readonly<boolean> = false>(
source: WatchSource<T>,
Expand Down Expand Up @@ -119,11 +124,14 @@ function doWatch(
}
})
} else if (isFunction(source)) { // function
if (cb) {
if (cb) { // watch函数
// @ts-ignore
getter = () => source()
} else {
getter = NOOP
} else { // 没有callback就是一个watchEffect
getter = () => {
// @ts-ignore
return source()
}
}
} else {
getter = NOOP
Expand All @@ -133,7 +141,7 @@ function doWatch(

let oldValue = isMultiSource ? [] : {}
const job: SchedulerJob = () => {
if (cb) {
if (cb) { // watch(source, callback)
const newValue = effect.run()
// 自己提出一个函数,源码里太长了不好阅读,功能一样
const _hasChange = () => {
Expand All @@ -147,6 +155,8 @@ function doWatch(

oldValue = newValue
}
} else { // watchEffect
effect.run()
}
}

Expand All @@ -167,6 +177,8 @@ function doWatch(
if (cb) {
// 先主动获取下,拿到旧值
oldValue = effect.run()
} else { // watchEffect
effect.run()
}
return function () {
// effect stop
Expand Down

0 comments on commit d04e878

Please sign in to comment.