0
0
Vueframework~5 mins

How Vue tracks dependencies automatically

Choose your learning style9 modes available
Introduction

Vue automatically knows which parts of your app need to update when data changes. This makes your app fast and easy to write.

When you want your app to update the screen automatically as data changes.
When you use reactive data in Vue components.
When you want to avoid manually telling Vue what to watch.
When you use computed properties or watchers in Vue.
When you want smooth and efficient UI updates without extra code.
Syntax
Vue
import { ref, computed, watchEffect } from 'vue'

const count = ref(0)

const double = computed(() => count.value * 2)

watchEffect(() => {
  console.log(`Count is ${count.value}`)
})

ref() creates reactive data Vue can track.

computed() creates a value that updates automatically when its dependencies change.

Examples
Here, greeting updates automatically when name changes.
Vue
import { ref, computed } from 'vue'

const name = ref('Alice')
const greeting = computed(() => `Hello, ${name.value}!`)
watchEffect runs the function immediately and reruns it whenever count changes.
Vue
import { ref, watchEffect } from 'vue'

const count = ref(0)

watchEffect(() => {
  console.log(`Count changed to ${count.value}`)
})
Sample Program

This Vue component shows a count and its double. When you click the button, count increases, and double updates automatically because Vue tracks the dependency.

Vue
<template>
  <div>
    <p>Count: {{ count }}</p>
    <p>Double: {{ double }}</p>
    <button @click="increment">Add 1</button>
  </div>
</template>

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

const count = ref(0)
const double = computed(() => count.value * 2)

function increment() {
  count.value++
}
</script>
OutputSuccess
Important Notes

Vue uses a system called reactivity to track which data your code uses.

When reactive data changes, Vue knows exactly which parts of your app to update.

This automatic tracking means you write less code and get faster updates.

Summary

Vue tracks dependencies automatically using reactive data like ref and computed.

This makes your app update only what needs to change, keeping it fast.

You don't have to manually tell Vue what to watch; it figures it out for you.