Vue.js Lesson 4: Reactivity — ref & reactive

💚 Vue.js CourseLesson 4 of 10 · 40% complete

Vue’s reactivity system is what makes the UI automatically update when data changes. Understanding ref vs reactive is essential.

ref — for primitives and single values

<script setup>
import { ref } from "vue";

// ref() wraps a value in a reactive container
const count = ref(0);
const name = ref("Alice");
const isActive = ref(false);

// In script: access .value
console.log(count.value); // 0
count.value++;             // triggers UI update
count.value = 10;

// In template: NO .value needed — Vue unwraps automatically
// <p>{{ count }}</p> — not count.value
</script>

reactive — for objects

<script setup>
import { reactive } from "vue";

// reactive() makes entire object reactive
const user = reactive({
  name: "Alice",
  age: 30,
  address: {
    city: "New York",
    country: "USA"
  }
});

// Direct access — no .value!
user.name = "Bob";          // triggers update
user.address.city = "LA";   // nested update works too!
</script>

// In template:
// <p>{{ user.name }} from {{ user.address.city }}</p>

When to Use Each

// Use ref() for:
// - Primitive values (string, number, boolean)
// - Arrays (though reactive([]) works too)
// - When you need to reassign the whole value

const items = ref([]);     // reassign: items.value = newArray;

// Use reactive() for:
// - Objects with multiple related properties
// - When you won't reassign the whole object

const form = reactive({ name: "", email: "", password: "" });

🏋️ Practice Task

Build a reactive form with reactive(): fields for name, email, age, bio. Show a live preview card below the form that updates as you type. Add a “Reset” button that clears all fields at once. Add a character count for bio (max 200 chars).

💡 Hint: Reset: Object.assign(form, {name:””,email:””,age:””,bio:””}). Character count: {{ form.bio.length }}/200

Similar Posts

Leave a Reply

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