0
0
Vueframework~5 mins

Composable accepting parameters in Vue

Choose your learning style9 modes available
Introduction

A composable is a reusable function in Vue that can accept parameters to customize its behavior. This helps you write clean and flexible code.

When you want to share logic between components but with different settings.
When you need to create a reusable feature that depends on input values.
When you want to keep your components simple by moving complex logic outside.
When you want to test logic separately by passing different parameters.
When you want to avoid repeating similar code with small differences.
Syntax
Vue
import { ref } from 'vue';

export function useExample(param) {
  const state = ref(param);
  function updateState(newVal) {
    state.value = newVal;
  }
  return { state, updateState };
}

The parameter param can be any value you want to customize the composable.

Use ref or reactive to create reactive state inside the composable.

Examples
This composable accepts a starting number and returns a counter with an increment function.
Vue
import { ref } from 'vue';

export function useCounter(start = 0) {
  const count = ref(start);
  function increment() {
    count.value++;
  }
  return { count, increment };
}
This composable creates a greeting message based on the passed name and allows updating it.
Vue
import { ref } from 'vue';

export function useGreeting(name) {
  const greeting = ref(`Hello, ${name}!`);
  function updateName(newName) {
    greeting.value = `Hello, ${newName}!`;
  }
  return { greeting, updateName };
}
Sample Program

This Vue component uses the useCounter composable with a starting value of 5. It shows the count and a button to increase it.

Vue
<script setup>
import { useCounter } from './useCounter';

const { count, increment } = useCounter(5);
</script>

<template>
  <div>
    <p>Count: {{ count }}</p>
    <button @click="increment">Add 1</button>
  </div>
</template>
OutputSuccess
Important Notes

Always pass parameters to composables to make them flexible and reusable.

Parameters can be simple values or objects for more complex configurations.

Use ref or reactive inside composables to keep state reactive.

Summary

Composable functions can accept parameters to customize their behavior.

This helps reuse logic with different inputs across components.

Use Vue's reactivity inside composables to keep state updated.