Mastering Vue 3 Composables: A Comprehensive Style Guide

The release of Vue 3 ushered in a transformational change, moving from the Options API to the Composition API. At the heart of this transition lies the concept of "composables" — modular functions that utilize Vue's reactive features. This change has injected greater flexibility and code reusability into the framework. However, it has also birthed challenges, notably the inconsistent implementation of composables across projects, which often results in convoluted and hard-to-maintain codebases.

This style guide aims to harmonize coding practices around composables, with a focus on producing clean, maintainable, and testable code. Though composables may appear to be a new beast, they are fundamentally just functions. Hence, this guide grounds its recommendations in time-tested principles of good software design.

Whether you're just stepping into Vue 3 or are an experienced developer aiming to standardize your team's coding style, this guide serves as a comprehensive resource.

Table of Contents

File Naming

Rule 1.1: Prefix with use and Follow PascalCase

// Good
useCounter.ts
useApiRequest.ts // Bad
counter.ts
APIrequest.ts

Composable Naming

Rule 2.1: Use Descriptive Names

// Good
export function useUserData() {} // Bad
export function useData() {}

Folder Structure

Rule 3.1: Place in composables Directory

src/
└── composables/
    ├── useCounter.ts
    └── useUserData.ts

Argument Passing

Rule 4.1: Use Object Arguments for Four or More Parameters

// Good: For Multiple Parameters
useUserData({ id: 1, fetchOnMount: true, token: 'abc', locale: 'en' }); // Also Good: For Fewer Parameters
useCounter(1, true, 'session'); // Bad
useUserData(1, true, 'abc', 'en');

Error Handling

Rule 5.1: Expose Error State

// Good
const error = ref(null);
try { // Do something
} catch (err) { error.value = err;
}
return { error }; // Bad
try { // Do something
} catch (err) { console.error("An error occurred:", err);
}
return {};

Avoid Mixing UI and Business Logic

Rule 6.2: Decouple UI from Business Logic in Composables

Composables should focus on managing state and business logic, avoiding UI-specific behavior like toasts or alerts. Keeping UI logic separate from business logic will ensure that your composable is reusable and testable.

// Good
export function useUserData(userId) { const user = ref(null); const error = ref(null); const fetchUser = async () => { try { const response = await axios.get(`/api/users/${userId}`); user.value = response.data; } catch (e) { error.value = e; } }; return { user, error, fetchUser };
} // In component
setup() { const { user, error, fetchUser } = useUserData(userId); watch(error, (newValue) => { if (newValue) { showToast("An error occurred."); // UI logic in component } }); return { user, fetchUser };
} // Bad
export function useUserData(userId) { const user = ref(null); const fetchUser = async () => { try { const response = await axios.get(`/api/users/${userId}`); user.value = response.data; } catch (e) { showToast("An error occurred."); // UI logic inside composable } }; return { user, fetchUser };
}

Anatomy of a Composable

Rule 7.2: Structure Your Composables Well

A composable that adheres to a well-defined structure is easier to understand, use, and maintain. Ideally, it should consist of the following components:

  • Primary State: The main read-only state that the composable manages.
  • Supportive State: Additional read-only states that hold values like the status of API requests or errors.
  • Methods: Functions responsible for updating the Primary and Supportive states. These can call APIs, manage cookies, or even call other composables.

By ensuring your composables follow this anatomical structure, you make it easier for developers to consume them, which can improve code quality across your project.

// Good Example: Anatomy of a Composable
// Well-structured according to Anatomy of a Composable
export function useUserData(userId) { // Primary State const user = ref(null); // Supportive State const status = ref('idle'); const error = ref(null); // Methods const fetchUser = async () => { status.value = 'loading'; try { const response = await axios.get(`/api/users/${userId}`); user.value = response.data; status.value = 'success'; } catch (e) { status.value = 'error'; error.value = e; } }; return { user, status, error, fetchUser };
} // Bad Example: Anatomy of a Composable
// Lacks well-defined structure and mixes concerns
export function useUserDataAndMore(userId) { // Muddled State: Not clear what's Primary or Supportive const user = ref(null); const count = ref(0); const message = ref('Initializing...'); // Methods: Multiple responsibilities and side-effects const fetchUserAndIncrement = async () => { message.value = 'Fetching user and incrementing count...'; try { const response = await axios.get(`/api/users/${userId}`); user.value = response.data; } catch (e) { message.value = 'Failed to fetch user.'; } count.value++; // Incrementing count, unrelated to user fetching }; // More Methods: Different kind of task entirely const setMessage = (newMessage) => { message.value = newMessage; }; return { user, count, message, fetchUserAndIncrement, setMessage };
}

Functional Core, Imperative Shell

Rule 8.2: (optional) use functional core imperative shell pattern

Structure your composable such that the core logic is functional and devoid of side effects, while the imperative shell handles the Vue-specific or side-effecting operations. Following this principle makes your composable easier to test, debug, and maintain.

Example: Functional Core, Imperative Shell

// good
// Functional Core
const calculate = (a, b) => a + b; // Imperative Shell
export function useCalculatorGood() { const result = ref(0); const add = (a, b) => { result.value = calculate(a, b); // Using the functional core }; // Other side-effecting code can go here, e.g., logging, API calls return { result, add };
} // wrong
// Mixing core logic and side effects
export function useCalculatorBad() { const result = ref(0); const add = (a, b) => { // Side-effect within core logic console.log("Adding:", a, b); result.value = a + b; }; return { result, add };
}

Single Responsibility Principle

Rule 9.1: Use SRP for composables

A composable should adhere to the Single Responsibility Principle, meaning it should have only one reason to change. In other words, a composable should have only one job or responsibility. A violation of this principle can result in composables that are difficult to understand, maintain, and test.

// Good
export function useCounter() { const count = ref(0); const increment = () => { count.value++; }; const decrement = () => { count.value--; }; return { count, increment, decrement };
} // Bad export function useUserAndCounter(userId) { const user = ref(null); const count = ref(0); const fetchUser = async () => { try { const response = await axios.get(`/api/users/${userId}`); user.value = response.data; } catch (error) { console.error("An error occurred while fetching user data:", error); } }; const increment = () => { count.value++; }; const decrement = () => { count.value--; }; return { user, fetchUser, count, increment, decrement };
}

File Structure of a Composable

Rule 10.1: Rule: Consistent Ordering of Composition API Features

While the precise order can be adapted to meet the needs of your project or team, it is crucial that the chosen order is maintained consistently throughout your codebase.

Here's a suggestion for a file structure:

  1. Initializing: Code for setting up initialization logic.
  2. Refs: Code for reactive references.
  3. Computed: Code for computed properties.
  4. Methods: Functions and methods that will be used.
  5. Lifecycle Hooks: Lifecycle hooks like onMounted, onUnmounted, etc.
  6. Watch

this is just one example of a possible order, its just important that you have a order and ideally in your project the order is always the same

// Example in useCounter.ts
import { ref, computed, onMounted } from "vue"; export default function useCounter() { // Initializing // Initialize variables, make API calls, or any setup logic // For example, using a router // ... // Refs const count = ref(0); // Computed const isEven = computed(() => count.value % 2 === 0); // Methods const increment = () => { count.value++; }; const decrement = () => { count.value--; }; // Lifecycle onMounted(() => { console.log("Counter is mounted"); }); return { count, isEven, increment, decrement, };
}

Conclusion

The guidelines presented in this article aim to offer best practices for writing clean, testable, and efficient Vue 3 composables. While these recommendations stem from a mix of established software design principles and practical experience, they are by no means exhaustive or universally applicable.

Programming is often more of an art than a science. As you grow in your Vue journey, you may find different strategies and patterns that work better for your specific use-cases. The key is to maintain a consistent, scalable, and maintainable codebase. Therefore, feel free to adapt these guidelines according to the needs of your project.

I'm open to further ideas, improvements, and real-world examples. If you have any suggestions or different approaches that work well for you, please don't hesitate to share in the comments below. Together, we can evolve these guidelines to be an even more useful resource for the Vue community.

Happy coding!

Enjoyed this post? Follow me on X for more Vue and TypeScript content:

@AlexanderOpalic

trang chủ - Wiki
Copyright © 2011-2024 iteam. Current version is 2.132.0. UTC+08:00, 2024-09-19 06:31
浙ICP备14020137号-1 $bản đồ khách truy cập$