Limitations of reactive() - replacing reactive objects
Version
3.2.31
Reproduction link
Steps to reproduce
Declare and initialize an object using reactive(). e.g. let state = reactive({ count: 0 })
Assign a different reactive value to the same object. e.g. state = reactive({ count: 1 })
What is expected?
The reactive object is not supposed to be "replaced"
What is actually happening?
The reactive object is replaced successfully, without losing its reactivity.
What is this statement supposed to mean?
" This means we can't easily 'replace' a reactive object " -> https://vuejs.org/guide/essentials/reactivity-fundamentals.html#reactive-proxy-vs-original-1
You're not changing the value of state.counter
, you're just assigning the variable state
to another reactive
object; only the second reactive object is returned by setup
.
For instance, if you have a watcher attached to the first reactive
, reactivity is completely lost.
As reactive
is just a JS object with a proxy, you could do something like:
state = Object.assign(state, { count: 1 })
But it's arguable if this is "easy".
What you describe is simply a limitation of the Javascript language. It offers no way for code to be alerted when when other code re-assigns a variable to a new value.
That's basically half of the reason why ref() exists.
If you need support in understanding this, we have a nice community at chat.vuejs.org. If you feel the docs could explain this better, please take it to the docs repository instead.
Raised a corresponsing issue on the docs repo. Thank you leopiccionia and LinusBorg