In Vue 3’s Composition API, props are inherently readonly, meaning they cannot be directly modified within a child component.

Understand the One-Way Data Flow: Props are designed to establish a one-way data flow from parent to child components. This ensures that the parent component has full control over the data, promoting predictable and maintainable code. Attempting to modify a prop directly within a child component will result in an error, as props are immutable by design.

1. To update a prop’s value correctly, you should follow these steps:

To enable a child component to request an update to a prop’s value, utilize the v-model directive. This pattern allows the child component to emit an event signaling the parent to update the prop.
-> In the Parent Component: Bind the v-model directive to the prop you wish to make reactive.
components

-> In the Child Component: Define the modelValue prop and emit an event to request an update to its value.
child-components

Note: If you’re using the script setup syntax, the implementation would look like this:

1. Parent Component (ParentComponent.vue)

In the parent component, bind a reactive state to the child component using the v-model directive:
p-compolnents

-> parentValue is a reactive reference initialized with ‘Initial Value’.​
-> The v-model directive binds parentValue to the child component, enabling two-way data binding.

2. Child Component (ChildComponent.vue)

In the child component, define the modelValue prop and emit the update:modelValue event to communicate changes back to the parent:
child-component

-> defineProps declares the modelValue prop, which receives the value from the parent component.​
-> defineEmits declares the update:modelValue event, which the child component emits to inform the parent of value changes.​
-> The updateValue function emits the update:modelValue event with the new value ‘New Value’.

2. Alternative Approach: Emit Custom Events: If you prefer not to use the v-model directive, you can achieve similar functionality by emitting custom events.

-> In the Parent Component: Listen for a custom event and update the prop accordingly.
p-components

-> In the Child Component: Emit a custom event with the new value when an update is needed.
child-components2

Alternative to v-model (Manual Binding)

Instead of v-model, you can manually bind the prop and listen for the update event:
alternate-modal

manuaaly-binding

Also Read

Also Read:

VueJs Projects

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