← Back to all snippets
JAVASCRIPT

Vue 3 Composition API: Reactivity, Computed, Watch

Master Vue 3's Composition API by learning how to use `ref`, `reactive`, `computed` properties, and `watch` effects for robust and organized component logic.

<template>
  <div>
    <h1>Counter: {{ count }}</h1>
    <p>Message: {{ state.message }}</p>
    <p>Doubled Count: {{ doubledCount }}</p>
    <button @click="increment">Increment</button>
    <button @click="changeMessage">Change Message</button>
  </div>
</template>

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

// 1. Using ref for primitive reactivity
const count = ref(0);

function increment() {
  count.value++;
}

// 2. Using reactive for object reactivity
const state = reactive({
  message: 'Hello Vue 3'
});

function changeMessage() {
  state.message = 'Updated Message!';
}

// 3. Using computed for derived reactive state
const doubledCount = computed(() => count.value * 2);

// 4. Using watch to react to changes
watch(count, (newCount, oldCount) => {
  console.log(`Count changed from ${oldCount} to ${newCount}`);
});

// Watch multiple sources
watch([count, () => state.message], ([newCount, newMessage], [oldCount, oldMessage]) => {
  console.log(`Count or message changed. New: ${newCount}, ${newMessage}`);
});
</script>

<style scoped>
/* Your styles here */
</style>
How it works: This snippet demonstrates the core features of Vue 3's Composition API. It uses `ref` to make primitive values like numbers reactive, `reactive` for objects, `computed` to create derived reactive properties that automatically update when their dependencies change, and `watch` to perform side effects in response to changes in reactive data. This approach promotes better organization and reusability of logic within components.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs