The reactive Function
The reactive function makes an object reactive in Vue. Vue tracks each property of the object, so the page updates when a property changes.
Create a reactive object
Start with a count of zero.
import { reactive } from 'vue'
const state = reactive({ count: 0 })Show a property
The template reads state.count.
<p>{{ state.count }}</p>Change a property
Assign a new number to state.count.
state.count = 4Two properties in one object
One object can hold a name and an age.
import { reactive } from 'vue'
const user = reactive({ name: 'Ana', age: 28 })Example
<script setup>
import { reactive } from 'vue'
const state = reactive({ count: 0, message: 'Hello' })
</script>
<template>
<div>
<p>{{ state.message }}</p>
<p>Count: {{ state.count }}</p>
</div>
</template>
Key points
- Call reactive with an object, like reactive({ count: 0 }).
- Read a property with its plain name, like state.count.
- Change a property with a plain assignment, like state.count = 1.
- No .value is needed for a reactive object.
- reactive works only on objects, not on single numbers.
In this example, the script imports reactive from Vue and makes a state object. The object holds a count and a message. The template shows the message and the count in two paragraphs. The page first shows Hello and Count: 0. If the script sets state.count to 1, the page shows Count: 1 instead.
Note
Use reactive for values that belong together in one object.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which value does reactive need?