0
0
VueConceptBeginner · 3 min read

What is Reactivity in Vue: Simple Explanation and Example

In Vue, reactivity means the framework automatically tracks changes to data and updates the user interface instantly. When you change a reactive variable, Vue detects it and refreshes only the parts of the page that depend on that data.
⚙️

How It Works

Think of Vue's reactivity like a smart assistant who watches your data closely. When you change something, the assistant quickly tells the parts of your app that use that data to update themselves. This way, you don't have to manually refresh or rewrite the page.

Under the hood, Vue uses special objects called reactive or ref that wrap your data. These objects keep track of who is using the data and notify them when it changes. It's like having a group chat where everyone interested in a topic gets notified when there's news.

💻

Example

This example shows a simple counter that updates on button click using Vue's reactivity.

vue
<template>
  <div>
    <p>Count: {{ count }}</p>
    <button @click="increment">Increase</button>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const count = ref(0)
function increment() {
  count.value++
}
</script>
Output
Count: 0 (initially) and increases by 1 each time the button is clicked
🎯

When to Use

Use Vue's reactivity whenever you want your app to respond instantly to user actions or data changes without reloading the page. It is perfect for forms, live counters, toggles, and any interactive UI elements.

For example, in a shopping cart, reactivity updates the total price as you add or remove items. It saves you from writing extra code to manually update the display.

Key Points

  • Reactivity means automatic UI updates when data changes.
  • Vue tracks reactive data using ref or reactive.
  • It improves user experience by keeping the interface in sync with data.
  • Use it for interactive and dynamic parts of your app.

Key Takeaways

Vue's reactivity automatically updates the UI when data changes.
Use ref or reactive to create reactive data in Vue.
Reactivity helps build interactive and dynamic user interfaces easily.
It reduces manual DOM updates and improves app performance.