#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
5 min read
Question 12 of 37medium

What are Composables in Vue?

Reusable stateful logic with composables.

What You'll Learn

  • What composables are
  • Creating composables
  • Best practices

What is a Composable?

A function that encapsulates and reuses stateful logic using Composition API.

Example: useMouse

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

export function useMouse() {
  const x = ref(0)
  const y = ref(0)

  function update(event) {
    x.value = event.pageX
    y.value = event.pageY
  }

  onMounted(() => window.addEventListener('mousemove', update))
  onUnmounted(() => window.removeEventListener('mousemove', update))

  return { x, y }
}

Usage

code.txtVUE
<script setup>
import { useMouse } from './composables/useMouse'

const { x, y } = useMouse()
</script>

<template>
  Mouse: {{ x }}, {{ y }}
</template>

Example: useFetch

code.jsJavaScript
export function useFetch(url) {
  const data = ref(null)
  const error = ref(null)
  const loading = ref(true)

  fetch(url)
    .then(res => res.json())
    .then(json => data.value = json)
    .catch(err => error.value = err)
    .finally(() => loading.value = false)

  return { data, error, loading }
}