Getting Started with Vue 3 Reactivity

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 and count are reactive thanks to ref
  • reactive() is used for objects (and arrays) that need to be reactive as a whole. We wrap the user object in reactive

Thanks to Vue’s reactivity system, any changes to these variables will automatically update the UI in real time.

Leave a Reply

Your email address will not be published. Required fields are marked *