0
0
Vueframework~5 mins

Composable naming conventions (use prefix) in Vue

Choose your learning style9 modes available
Introduction

Using prefixes in composable names helps keep your code clear and organized. It shows what the composable does and avoids name clashes.

When creating reusable logic pieces in Vue 3 using the Composition API.
When you want to clearly identify composables related to a specific feature or domain.
When working in a team to make composable purposes obvious at a glance.
When you want to avoid naming conflicts with other composables or variables.
When you want to improve code readability and maintainability.
Syntax
Vue
function usePrefixFeatureName() {
  // composable logic here
  return { /* reactive data or methods */ };
}

Start composable names with use to follow Vue community conventions.

Add a clear prefix that groups related composables, like useAuth or useCart.

Examples
This composable handles login logic and is clearly part of the auth group.
Vue
function useAuthLogin() {
  // logic for login
  return { loginUser };
}
This composable manages shopping cart items, grouped under 'cart'.
Vue
function useCartItems() {
  // logic for cart items
  return { items };
}
This composable deals with user profile data, grouped under 'user'.
Vue
function useUserProfile() {
  // logic for user profile
  return { profile };
}
Sample Program

This example shows a composable named useCounter that manages a count state. The prefix use indicates it is a composable. The component uses this composable to display and increment the count.

Vue
import { ref } from 'vue';

// Composable with prefix 'useCounter'
export function useCounter() {
  const count = ref(0);
  function increment() {
    count.value++;
  }
  return { count, increment };
}

// Vue component using the composable
import { defineComponent } from 'vue';
import { useCounter } from './useCounter';

export default defineComponent({
  setup() {
    const { count, increment } = useCounter();
    return { count, increment };
  },
  template: `<button @click="increment">Count: {{ count }}</button>`
});
OutputSuccess
Important Notes

Always use the use prefix for composables to follow Vue style.

Choose prefixes that describe the feature or domain clearly.

Keep composable names short but descriptive to improve readability.

Summary

Composable names should start with use to show they are composables.

Use prefixes to group related composables and avoid confusion.

Clear naming helps you and others understand your code faster.