Vue 3 brings a powerful, flexible, and intuitive reactivity system built on ref()
and reactive()
. If you’re transitioning from Vue 2 or just starting out, this guide will help you understand how to bind data using these new tools with real-time updates in your UI.
Code Example
Here’s a simple example showing both ref
and reactive
in action:
<template>
<h2>Hello Vue World</h2>
<h4>{{ name }}</h4>
<p>Email: {{ user.email }}</p>
<p>Count: {{ count }}</p>
<input type="text" v-model="name" placeholder="Change name" />
<input type="email" v-model="user.email" placeholder="Change email" />
<button @click="count++">Click Count: {{ count }}</button>
</template>
<script setup>
import { ref, reactive } from 'vue'
// ref for primitive values
const name = ref("Marcel Don")
const count = ref(0)
// reactive for objects
const user = reactive({
email: "marcel@gmail.com"
})
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
text-align: center;
margin-top: 60px;
}
input {
display: block;
margin: 10px auto;
padding: 5px;
}
</style>
Explanation
ref()
is used for primitive values like strings, numbers, or booleans. Also,name
andcount
are reactive thanks toref
reactive()
is used for objects (and arrays) that need to be reactive as a whole. We wrap theuser
object inreactive
Thanks to Vue’s reactivity system, any changes to these variables will automatically update the UI in real time.