← Back to all snippets
JAVASCRIPT

Create Reusable Logic with Vue 3 Composables (Composition API)

Leverage Vue 3's Composition API to create composables, enabling highly reusable and organized reactive logic across multiple components, enhancing maintainability.

// src/composables/useCounter.js
import { ref, computed } from 'vue';

export function useCounter(initialValue = 0) {
  const count = ref(initialValue);

  const increment = () => {
    count.value++;
  };

  const decrement = () => {
    count.value--;
  };

  const doubleCount = computed(() => count.value * 2);

  return {
    count,
    increment,
    decrement,
    doubleCount
  };
}

// src/components/MyComponent.vue
<template>
  <div>
    <p>Count: {{ count }}</p>
    <p>Double Count: {{ doubleCount }}</p>
    <button @click="increment">Increment</button>
    <button @click="decrement">Decrement</button>
  </div>
</template>

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

const { count, increment, decrement, doubleCount } = useCounter(10);
</script>

// src/components/AnotherComponent.vue (demonstrates reuse)
<template>
  <div>
    <h2>Another Counter</h2>
    <p>Value: {{ count }}</p>
    <button @click="increment">Add One</button>
  </div>
</template>

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

const { count, increment } = useCounter(100);
</script>
How it works: This snippet illustrates creating and using a Vue 3 composable (`useCounter`). A composable is a function that leverages Vue's Composition API to encapsulate reusable reactive stateful logic. It returns reactive references (`ref`), computed properties (`computed`), and functions, which are then destructured and used directly in the `setup` script of a component. This promotes modularity and code reuse without mixins.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs