Ref and reactive help you keep track of data that changes in your Vue app. They make your app update automatically when data changes.
0
0
Ref and reactive in Composition API in Vue
Introduction
When you want to store a simple value like a number or string that changes over time.
When you need to keep an object or array reactive so Vue updates the UI when it changes.
When building components that need to respond to user input or events.
When you want to share reactive data between functions inside the setup() function.
When you want Vue to watch and react to changes in your data automatically.
Syntax
Vue
import { ref, reactive } from 'vue'; const count = ref(0); const user = reactive({ name: 'Alice', age: 25 });
ref is for simple values like numbers, strings, or booleans.
reactive is for objects and arrays to make all their properties reactive.
Examples
This creates a reactive string value. Use
message.value to get or set it.Vue
const message = ref('Hello');
This creates a reactive object. You can access properties like
user.name.Vue
const user = reactive({ name: 'Bob', age: 30 });
Update the value inside a
ref by changing its .value property.Vue
message.value = 'Hi there!';Update a property inside a
reactive object directly.Vue
user.age = 31;Sample Program
This Vue component uses ref for a simple number and reactive for an object. Buttons update the values, and the UI updates automatically.
Vue
<script setup> import { ref, reactive } from 'vue'; const count = ref(0); const user = reactive({ name: 'Emma', age: 28 }); function increment() { count.value++; } function haveBirthday() { user.age++; } </script> <template> <div> <p>Count: {{ count }}</p> <button @click="increment">Increase Count</button> <p>User: {{ user.name }}, Age: {{ user.age }}</p> <button @click="haveBirthday">Have Birthday</button> </div> </template>
OutputSuccess
Important Notes
Always use .value to read or write a ref value inside JavaScript.
For reactive objects, access and update properties directly without .value.
Use ref for simple data and reactive for complex objects or arrays.
Summary
ref holds simple reactive values accessed with .value.
reactive makes objects and arrays reactive with direct property access.
Both help Vue update the UI automatically when data changes.