Core Concepts

Reactivity

Understand Vue's reactivity system with ref, reactive, computed properties, and watchers.

ref vs reactive

  • `ref()`: For primitive values (numbers, strings, booleans). Access/mutate via .value
  • `reactive()`: For objects and arrays. No .value needed

Computed Properties

Computed properties are derived state — they automatically update when their dependencies change, and cache their results.

Watchers

Use watch and watchEffect to run side effects when reactive state changes.

  • `watch`: Watch specific sources, access old and new values
  • `watchEffect`: Automatically tracks reactive dependencies used inside

Example

javascript
<script setup>
import { ref, reactive, computed, watch, watchEffect } from 'vue';

// ref - for primitives
const count = ref(0);
const name = ref('Alice');
count.value++;         // must use .value in script
// In template: {{ count }} (no .value needed)

// reactive - for objects
const user = reactive({
  name: 'Bob',
  age: 30,
  address: { city: 'Paris' }
});
user.age++;             // no .value needed
user.address.city = 'London';

// Computed properties
const doubled = computed(() => count.value * 2);
const fullName = computed({
  get: () => `${user.firstName} ${user.lastName}`,
  set: (val) => {
    const [first, last] = val.split(' ');
    user.firstName = first;
    user.lastName = last;
  }
});

// watch - explicit source
watch(count, (newVal, oldVal) => {
  console.log(`count changed from ${oldVal} to ${newVal}`);
});

// watch multiple sources
watch([count, name], ([newCount, newName]) => {
  console.log(newCount, newName);
});

// watchEffect - auto-tracks dependencies
watchEffect(() => {
  console.log(`count is now: ${count.value}`);
  document.title = `Count: ${count.value}`;
});
</script>
Try it yourself — JAVASCRIPT