Composables in Vue.js

From the Vue.js cheat sheet · Advanced Features · verified Jul 2026

Composables

Reusable composition functions

javascript
// composables/useMouse.js
import { ref, onMounted, onUnmounted } from 'vue'

export function useMouse() {
  const x = ref(0)
  const y = ref(0)
  
  function update(e) {
    x.value = e.pageX
    y.value = e.pageY
  }
  
  onMounted(() => window.addEventListener('mousemove', update))
  onUnmounted(() => window.removeEventListener('mousemove', update))
  
  return { x, y }
}

// Using composable
<script setup>
import { useMouse } from './composables/useMouse'
const { x, y } = useMouse()
</script>
💡 Composables extract and reuse stateful logic
⚡ Convention: composable names start with "use"
📌 Composables can only be called in setup or other composables
🔥 Return refs to maintain reactivity when destructuring

More Vue.js tasks

Back to the full Vue.js cheat sheet