Reactivity Basics & Composition API (ref & reactive)
Vue 3's Composition API provides a more flexible way to structure components, using reactivity functions like ref and reactive to define state properties.
1 ref() vs reactive()
Reactivity functions serve different use cases:
- ref(): Can wrap any value (primitives like strings, numbers, booleans, or objects). In JavaScript scripts, you must access the value using
.value(e.g.count.value++). Inside<template>layout, it is automatically unwrapped, so no.valueis needed. - reactive(): Can only wrap object types (objects, arrays). It does not use
.value, but you cannot reassign the root object reference without losing reactivity. - <script setup>: Syntactic sugar that simplifies using the Composition API, automatically exposing declared variables to the template.
2 Composition API Setup in SFC
Let's check how to write a component using the Composition API with <script setup>:
Vue — Script Setup SFC
<template>
<div class="profile">
<h3>User: {{ profile.name }}</h3>
<p>Age: {{ profile.age }}</p>
<button @click="birthday">Birthday</button>
</div>
</template>
<script setup>
import { ref, reactive } from 'vue';
// ref for a simple boolean flag
const isActive = ref(true);
// reactive for an object
const profile = reactive({
name: 'Balaji Nayak',
age: 22
});
function birthday() {
// Access and modify properties directly
profile.age++;
}
</script>
3 Code Challenge
Challenge: Write a component containing a reactive state array of colors using
ref(). Add a method that pushes a new color string to the array when a button is clicked.