In Vue 3, computed properties are reactive by default and should update when their dependencies change.
However, when you reassign the entire reactive object, the computed property might not update as expected.
This is because Vue's reactivity system tracks changes at the property level, rather than at the object level.
To ensure that the computed property updates when the reactive object is reassigned, you can use a combination of a ref and a computed property.
Here's an example:
import { reactive, computed, ref } from 'vue';
const myData = ref(reactive({
firstName: 'John',
lastName: 'Doe'
}));
const fullName = computed(() => {
return `${myData.value.firstName} ${myData.value.lastName}`;
});
console.log(fullName.value); // Output: "John Doe"
myData.value = reactive({
firstName: 'Jane',
lastName: 'Smith'
});
console.log(fullName.value); // Output: "Jane Smith"
In this example, we wrap the reactive object in a ref using the ref function.
By doing this, we create a new reactive reference to the object itself. When the reactive object is reassigned, the ref will update, triggering the computed property to recalculate and update accordingly.
Using this approach, the computed property will remain reactive even when the reactive object is reassigned.