Vue · Middle · Question 20 of 75

What is a composable?

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

Explanation

Each call creates its own state. By convention composables are named useXxx, called synchronously in setup, and return refs. VueUse is a large collection of ready-made ones.

Further reading

Problem with a question

Vue · Middle · question 20

Test yourself

Take the Vue · Middle quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz