0
0
Vueframework~5 mins

Why composables matter in Vue

Choose your learning style9 modes available
Introduction

Composables help you reuse code easily in Vue. They keep your code clean and organized by sharing logic across components.

You want to share the same logic between multiple components without repeating code.
You need to separate complex logic from the UI to make your components simpler.
You want to test your logic independently from the component.
You want to keep your code organized as your app grows bigger.
You want to improve readability by grouping related logic in one place.
Syntax
Vue
import { ref } from 'vue'

export function useCounter() {
  const count = ref(0)
  function increment() {
    count.value++
  }
  return { count, increment }
}
Composables are just regular JavaScript functions that use Vue's reactive features.
They usually start with 'use' to show they provide reusable logic.
Examples
This composable manages a simple toggle state that can be reused in any component.
Vue
import { ref } from 'vue'

export function useToggle() {
  const isOn = ref(false)
  function toggle() {
    isOn.value = !isOn.value
  }
  return { isOn, toggle }
}
This composable tracks the window width reactively and updates when the window resizes.
Vue
import { ref, onMounted, onUnmounted } from 'vue'

export function useWindowWidth() {
  const width = ref(window.innerWidth)
  function updateWidth() {
    width.value = window.innerWidth
  }
  onMounted(() => {
    window.addEventListener('resize', updateWidth)
  })
  onUnmounted(() => {
    window.removeEventListener('resize', updateWidth)
  })
  return { width }
}
Sample Program

This Vue component uses the useCounter composable to add a counter button. Clicking the button increases the count.

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

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

<template>
  <button @click="increment" aria-label="Increment counter">Count: {{ count }}</button>
</template>
OutputSuccess
Important Notes

Always name composables starting with 'use' to keep your code clear.

Composables help separate logic from UI, making components easier to read and maintain.

Use composables to share logic without copying code between components.

Summary

Composables let you reuse logic easily in Vue apps.

They keep your components simple and clean.

Use composables to organize and share code better.