🎓 A1Learner
🔍
0 of 50 lessons completed

Composable Functions

A composable is a plain function that holds reusable Vue logic. It creates refs and functions and returns them for a component to use.

The composable

useToggle holds one ref and one function.

function useToggle() {
  const on = ref(false)
  function toggle() { on.value = !on.value }
  return { on, toggle }
}

Use it in setup

The component takes on and toggle from useToggle.

const { on, toggle } = useToggle()

The switch on the page

on is false, so the paragraph shows Off.

<p>{{ on ? 'On' : 'Off' }}</p>

Example

<script setup>
import { ref } from 'vue'
function useToggle() {
  const on = ref(false)
  function toggle() {
    on.value = !on.value
  }
  return { on, toggle }
}
const { on, toggle } = useToggle()
</script>
<template>
  <div>
    <p>{{ on ? 'On' : 'Off' }}</p>
    <button @click="toggle">Switch</button>
  </div>
</template>

Key points

  • A composable name starts with use, like useToggle.
  • It calls ref and other Vue functions inside its own body.
  • It returns an object with the refs and functions the component needs.
  • A component calls the composable inside script setup and uses what it returns.
  • Two components can call the same composable, and each gets its own fresh state.

In this example, useToggle is a plain function in the same file. It creates a ref named on with the value false. It defines toggle, which flips on. It returns both in an object. The component calls useToggle inside script setup. The template shows On or Off from on, and the button calls toggle. The first render shows Off. A verified variant with on set to true shows On.

Note

A composable is a plain function, not a component, so it has no template.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does a composable return?