Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(runtime-core): support deep: false when watch reactive #9928

Merged
merged 4 commits into from Dec 30, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
32 changes: 32 additions & 0 deletions packages/runtime-core/__tests__/apiWatch.spec.ts
Expand Up @@ -156,6 +156,38 @@ describe('api: watch', () => {
expect(dummy).toBe(1)
})

it('directly watching reactive object: deep: false', async () => {
const src = reactive({
state: {
count: 0
}
})
let dummy
watch(
src,
({ state }) => {
dummy = state
},
{
deep: false
}
)
src.state.count++
await nextTick()
expect(dummy).toBe(undefined)
})

it('directly watching reactive array', async () => {
const src = reactive([0])
let dummy
watch(src, v => {
dummy = v
})
src.push(1)
await nextTick()
expect(dummy).toMatchObject([0, 1])
})

it('watching multiple sources', async () => {
const state = reactive({ count: 1 })
const count = ref(1)
Expand Down
25 changes: 23 additions & 2 deletions packages/runtime-core/src/apiWatch.ts
Expand Up @@ -209,8 +209,9 @@ function doWatch(
getter = () => source.value
forceTrigger = isShallow(source)
} else if (isReactive(source)) {
getter = () => source
deep = true
deep = isShallow(source) ? false : deep ?? true
getter = deep ? () => source : () => shallowTraverse(source)
forceTrigger = true
} else if (isArray(source)) {
isMultiSource = true
forceTrigger = source.some(s => isReactive(s) || isShallow(s))
Expand Down Expand Up @@ -464,3 +465,23 @@ export function traverse(value: unknown, seen?: Set<unknown>) {
}
return value
}

export function shallowTraverse(value: unknown) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should be able to reuse traverse by adding a second argument:

traverse(value: unknown, shallow = false, seen?: Set<unknown>)

if (!isObject(value) || (value as any)[ReactiveFlags.SKIP]) {
return value
}
if (isArray(value)) {
for (let i = 0; i < value.length; i++) {
value[i]
}
} else if (isSet(value) || isMap(value)) {
value.forEach((v: any) => {
v
})
} else if (isPlainObject(value)) {
for (const key in value) {
value[key]
}
}
return value
}