Article 5

Vue.js 3 Composition API Guide

Master Vue.js 3 Composition API with this guide to reactive state, composables, lifecycle hooks, and best practices for modern web development.

1. Introduction to Vue.js 3 and Composition API

Vue.js 3 is a progressive JavaScript framework for building user interfaces. The Composition API, introduced in Vue 3, offers a flexible and powerful way to manage component logic, replacing the Options API for more complex applications.

The Composition API allows developers to organize code by logical concern, making it easier to reuse and maintain code compared to the Options API.

💡 Why Use Composition API?
  • Better code organization and reusability
  • Improved TypeScript support
  • More flexible component logic
  • Simpler handling of reactive state

1.1 Composition vs. Options API

  • Options API: Organized by options (data, methods, computed)
  • Composition API: Organized by logical concerns using reactive APIs
  • Use Case: Composition API shines in large, complex applications

2. Reactive State

The Composition API uses ref and reactive to create reactive state, enabling automatic UI updates when data changes.

2.1 Using ref

ref creates a reactive reference to a single value.

2.2 Using reactive

reactive creates a reactive object for complex state.

💡 Pro Tip: Use ref for primitive values and reactive for objects to optimize reactivity.

3. Composables

Composables are reusable functions that encapsulate reactive logic, similar to custom hooks in React.

3.1 Creating a Composable

// useCounter.js import { ref } from 'vue'; export function useCounter() { const count = ref(0); function increment() { count.value++; } function decrement() { count.value--; } return { count, increment, decrement }; }

3.2 Using a Composable

4. Lifecycle Hooks

The Composition API provides lifecycle hooks as functions, offering fine-grained control over component lifecycle.

4.1 Common Lifecycle Hooks

⚠️ Note: Always clean up resources (e.g., timers, event listeners) in onUnmounted to prevent memory leaks.

5. Refs vs. Reactive

Choosing between ref and reactive depends on your use case.

5.1 When to Use Each

  • ref: For single values (strings, numbers, booleans)
  • reactive: For objects or complex state
  • Considerations: ref requires .value, while reactive objects are deeply reactive

6. Vue Router

Vue Router enables client-side routing for Vue.js applications.

6.1 Basic Routing

// router.js import { createRouter, createWebHistory } from 'vue-router'; import Home from './views/Home.vue'; import About from './views/About.vue'; const router = createRouter({ history: createWebHistory(), routes: [ { path: '/', component: Home }, { path: '/about', component: About } ] }); export default router;

6.2 Navigation

7. State Management with Pinia

Pinia is the recommended state management library for Vue 3, offering a simpler API than Vuex.

7.1 Defining a Store

// store/counter.js import { defineStore } from 'pinia'; export const useCounterStore = defineStore('counter', { state: () => ({ count: 0 }), actions: { increment() { this.count++; } }, getters: { doubleCount: (state) => state.count * 2 } });

7.2 Using a Store

💡 Pinia Benefits: Type-safe, modular, and integrates seamlessly with Vue 3's reactivity system.

8. Best Practices

Follow these guidelines for maintainable and efficient Vue 3 code.

8.1 Component Design

  • Use <script setup> for concise syntax
  • Extract reusable logic into composables
  • Keep components focused and single-purpose

8.2 Common Pitfalls

⚠️ Common Mistakes:
  • Not unwrapping refs in templates (use {{ count }}, not {{ count.value }})
  • Overusing reactive for simple state
  • Forgetting to clean up side effects in onUnmounted
  • Ignoring TypeScript for large projects

8.3 Accessibility

9. Conclusion

Vue.js 3's Composition API revolutionizes how we build Vue applications, offering flexibility, reusability, and better TypeScript integration. By mastering reactive state, composables, and modern tools like Pinia and Vue Router, you can create robust, scalable applications.

Key takeaways:

  • Composition API organizes logic by concern
  • ref and reactive enable reactive state
  • Composables promote code reuse
  • Pinia simplifies state management
  • Vue Router handles client-side navigation

Start building Vue 3 apps by experimenting with small projects and integrating with modern tools like Vite and Pinia.

🎯 Next Steps:
  • Build a todo list app with Composition API
  • Create a custom composable for data fetching
  • Integrate Pinia with a multi-page Vue Router app