Vue 3 Composition API
Build reusable, maintainable Vue components with the Composition API.
Basic Setup
<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
// Reactive state
const count = ref(0);
const user = reactive({ name: '', email: '' });
// Computed property
const doubleCount = computed(() => count.value * 2);
// Methods
const increment = () => count.value++;
// Lifecycle
onMounted(() => {
console.log('Component mounted');
});
</script>
<template>
<button @click="increment">Count: {{ count }}</button>
<p>Double: {{ doubleCount }}</p>
</template>
Creating Composables
// composables/useFetch.js
import { ref, watchEffect } from 'vue';
export function useFetch(url) {
const data = ref(null);
const error = ref(null);
const loading = ref(true);
watchEffect(async () => {
loading.value = true;
try {
const response = await fetch(url.value);
data.value = await response.json();
} catch (e) {
error.value = e;
} finally {
loading.value = false;
}
});
return { data, error, loading };
}
Using Composables
<script setup>
import { ref } from 'vue';
import { useFetch } from '@/composables/useFetch';
const url = ref('/api/users');
const { data: users, loading, error } = useFetch(url);
</script>
<template>
<div v-if="loading">Loading...</div>
<div v-else-if="error">Error: {{ error.message }}</div>
<ul v-else>
<li v-for="user in users" :key="user.id">{{ user.name }}</li>
</ul>
</template>
Composables enable clean separation of concerns and code reuse across components.
Comments (0)
Leave a Comment
No comments yet. Be the first to share your thoughts!