Solution for Why toRefs is not working as expected in Vue 3?
is Given Below:
I have created a custom hook useDialog()
, where I return a params
object which is wrapped inside a computed
function.
// useDialog hook
...
params = computed(() => something(dependingOnRef));
...
// script
setup() {
...
const { params } = useDialog();
...
return {
params,
}
}
// template
<div>{{ JSON.stringify( { params } ) }} </div>
Everything works as expected. Once I change dependingOnRef
value, the params get updated and the view changes.
BUT !!
when I use toRefs
to destruct / spread the params
object, I do not have the same reactivity.
For example:
// script
setup() {
...
const { params } = useDialog();
const { name } = toRefs(params);
...
return {
params,
name,
}
}
// template
<div>{{ JSON.stringify( { params }) }} </div>
<div>{{ JSON.stringify( { name }) }} </div>
In my view I get:
{"params":{"id":9,"name":"Some name"}}
but an empty object for { name }
{}
Why is this happening ? Shouldn’t the view also be reactive to name
property of params
object ?