Copied to Clipboard
Learn the difference between ref and reactive here.
2. Computed Properties
computed is used to create reactive, derived data based on other reactive values.
<script setup>
import { ref, computed } from 'vue';
const count = ref(0);
const double = computed(() => count.value * 2);
</script>
<template>
<div>
<p>Count: {{ count }}</p>
<p>Double: {{ double }}</p>
</div>
</template>
3. Watchers
watch observes reactive values and performs actions when they change.
<script setup>
import { ref, watch } from 'vue';
const count = ref(0);
watch(count, (newValue, oldValue) => {
console.log(`Count changed from ${oldValue} to ${newValue}`);
});
</script>
<template>
<div>
<p>Count: {{ count }}</p>
</div>
</template>
4. Lifecycle Hooks
The Composition API offers equivalent lifecycle hooks as functions.
<script setup>
import { onMounted, onUnmounted } from 'vue';
onMounted(() => {
console.log('Component mounted');
});
onUnmounted(() => {
console.log('Component unmounted');
});
</script>
5. Composables
A composable is a reusable function that encapsulates logic. It’s a cornerstone of the Composition API’s reusability.
Example: Composable for Counter Logic
// useCounter.js
import { ref } from 'vue';
export function useCounter() {
const count = ref(0);
const increment = () => {
count.value++;
};
const decrement = () => {
count.value--;
};
return { count, increment, decrement };
}
Using the Composable:
<script setup>
import { useCounter } from './useCounter';
const { count, increment, decrement } = useCounter();
</script>
<template>
<div>
<p>Count: {{ count }}</p>
<button @click="increment">Increment</button>
<button @click="decrement">Decrement</button>
</div>
</template>
Learn more about good practices and design patterns for Vue composables here
📖 Learn more
If you would like to learn more about Vue, Nuxt, JavaScript or other useful technologies, checkout VueSchool by clicking this link or by clicking the image below:
Vue School Link
It covers most important concepts while building modern Vue or Nuxt applications that can help you in your daily work or side projects 😉
✅ Summary
The Vue 3 Composition API provides a modern, flexible way to handle state and logic, making your applications easier to scale and maintain. By understanding and using reactive primitives, computed properties, watchers, and composables, you can write cleaner and more reusable code.
Start experimenting with the Composition API today to unlock its full potential!
Take care and see you next time!
And happy coding as always 🖥️