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

Watchers for arrays don't fire on 'add' triggers #1351

Closed
Jexordexan opened this issue Jun 12, 2020 · 3 comments
Closed

Watchers for arrays don't fire on 'add' triggers #1351

Jexordexan opened this issue Jun 12, 2020 · 3 comments

Comments

@Jexordexan
Copy link

Version

3.0.0-beta.14

Reproduction link

https://codesandbox.io/s/vue-3-watcher-error-goox1

Steps to reproduce

I assume that when watching an array, the watcher would fire when items are added.

const state = reactive({ items: [] })

watchEffect(() => console.log(state.items))

state.items.push('foo')  // expect watcher to fire

What is expected?

the watchEffect fires when items are added to the array

What is actually happening?

the watchEffect does not fire

@yyx990803
Copy link
Member

yyx990803 commented Jun 12, 2020

This is expected behavior. state.items only tracks the mutation of the .items binding, it doesn't track deep mutations of the items array itself.

You can either add { deep: true }, which is inefficient, or replace the array with state.items = state.items.concat('foo').

If you actually iterate over the array in the watcher callback, then it will track array mutations automatically.

@Jexordexan
Copy link
Author

Ok, fair! I figured it might be intentional. My next question is why it triggers when I just watch the state object, even with deep: false. for example:

const state = reactive({ items: [] })

watch(state, () => console.log('watcher fired'), { deep: false } )

state.items.push('foo')  // the watcher DOES fire in this case

@yyx990803
Copy link
Member

When you directly watch a reactive object, it is implicitly deep because it would be pointless if it's not a deep watch.

@github-actions github-actions bot locked and limited conversation to collaborators Nov 11, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants