0
0
VueConceptBeginner · 3 min read

What is Composable in Vue: Simple Explanation and Example

In Vue, a composable is a reusable function that uses Vue's Composition API to share reactive logic across components. It helps organize code by extracting common behavior into simple, reusable pieces.
⚙️

How It Works

A composable in Vue is like a small tool you create to handle a specific task or logic that you want to use in many places. Imagine you have a recipe for making a sandwich that you want to share with friends. Instead of explaining it every time, you write it down once and give it to them. Similarly, a composable is a function that holds reactive state and logic, which you can use in multiple components.

Under the hood, composables use Vue's reactive or ref to keep track of data changes and watch or other Composition API features to react to those changes. When you call a composable inside a component's setup function, it returns reactive data and methods that the component can use, keeping your code clean and organized.

💻

Example

This example shows a simple composable that tracks a counter and provides functions to increase or reset it. You can use this composable in any component to share the same counter logic.

javascript
import { ref } from 'vue';

export function useCounter() {
  const count = ref(0);
  function increment() {
    count.value++;
  }
  function reset() {
    count.value = 0;
  }
  return { count, increment, reset };
}

// Usage in a component
import { defineComponent } from 'vue';
import { useCounter } from './useCounter';

export default defineComponent({
  setup() {
    const { count, increment, reset } = useCounter();
    return { count, increment, reset };
  }
});
Output
When used in a component template, it shows the current count and buttons to increase or reset it.
🎯

When to Use

Use composables when you have logic or state that needs to be shared across multiple components. For example, fetching data from an API, handling form inputs, or managing timers. Instead of copying code, you write a composable once and reuse it, making your app easier to maintain and test.

They are especially helpful in medium to large projects where many components share similar behavior. Composables keep your code DRY (Don't Repeat Yourself) and improve readability.

Key Points

  • Composable is a reusable function using Vue's Composition API.
  • It returns reactive state and methods to components.
  • Helps share logic without repeating code.
  • Improves code organization and maintainability.
  • Used inside the setup() function of components.

Key Takeaways

A composable is a reusable function that shares reactive logic in Vue components.
It uses Vue's Composition API features like ref and reactive.
Composables help keep code clean and avoid repetition.
Use composables to share stateful logic across multiple components.
They improve maintainability and readability in Vue apps.