Skip to content

Vue composables

Implementation guidelines

  • Encapsulation: keep business logic self-contained and return only the reactive state and functions components need.
  • When to use: use a composable when the logic depends on reactive data or computed values. Otherwise write a util.
  • Single responsibility: one composable covers one aspect of application logic.

Example: useCounter

import { ref } from "vue";

export const useCounter = (defaultValue: number = 0) => {
  const count = ref<number>(defaultValue);

  function increment(): void {
    count.value++;
  }

  return { count, increment };
}

Usage

<template>
  <div>
    <p>Current Count: {{ count }}</p>
    <button @click="increment">Increment</button>
  </div>
</template>

<script setup lang="ts">
  import { useCounter } from "@/src/shared/composables/useCounter";

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