In Vue 3, when accessing props within the setup function, directly destructuring them can lead to a loss of reactivity. This means that changes to the prop in the parent component might not be reflected in the child component. To maintain reactivity, you should use Vue’s toRefs or toRef utilities.

Here’s a step-by-step guide to address this issue:

1. Understand the Problem:

When you destructure props directly in the setup function, Vue loses track of their reactivity.
For example:
problem-1

In this case, courseId is no longer reactive, and updates to the prop won’t trigger reactivity in the child component.

2. Solution Using toRefs:

The toRefs function creates reactive references to each property of a reactive object.​
to-refs

Now, courseId remains reactive, and any changes to the prop in the parent component will be reflected in the child component.

3. Solution Using toRef:

If you only need to make a single prop reactive, toRef can be used:​
using-torefs

This approach is efficient when you only need reactivity for one specific prop.​

4. Using defineProps in {script setup}:

define-props

Here, defineProps returns a reactive object, and using toRefs ensures that each prop maintains its reactivity.

Need Help With Vue Development?

Work with our skilled Vue developers to accelerate your project and boost its performance.

Hire Vuejs Developers

Support On Demand!

Related Q&A