Frontend Development 2 min read 1,245 views

Vue 3 Composition API: Building Reusable Components and Composables

Master Vue 3 Composition API to build reusable components and composables. Learn about reactivity, lifecycle hooks, and state management.

E
Vue.js development

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.

Share this article:
ES

Written by Edrees Salih

Full-stack software engineer with 9 years of experience. Passionate about building scalable solutions and sharing knowledge with the developer community.

View Profile

Comments (0)

Leave a Comment

Your email will not be published.

No comments yet. Be the first to share your thoughts!