Skip to content

Vue Composition API Explained — Building with Composables

DodaTech Updated 2026-06-28 1 min read

In this tutorial, you will learn about Vue Composition API Explained. We cover key concepts, practical examples, and best practices to help you master this topic.

The Composition API provides a flexible way to organize component logic by composition. Instead of options-based organization, logic is grouped by feature using composable functions.

What You'll Learn

  • setup function basics
  • ref vs reactive
  • Computed and watch in setup
  • Creating composable functions
  • Options API vs Composition API

Why It Matters

The Composition API solves logic duplication and organization issues in large components, enabling true code reuse through composable functions independent of component structure.

<template>
  <div>
    <p>Mouse position: {{ x }}, {{ y }}</p>
    <button @click="toggle">Toggle visibility</button>
    <div v-if="visible">
      <p v-for="item in sortedItems" :key="item">{{ item }}</p>
    </div>
  </div>
</template>

<script setup>
import { useMousePosition } from "./composables/useMousePosition";
import { useSortedList } from "./composables/useSortedList";
import { ref } from "vue";

const { x, y } = useMousePosition();
const { sortedItems } = useSortedList(["banana", "apple", "cherry"]);
const visible = ref(true);
function toggle() { visible.value = !visible.value; }
</script>
// composables/useMousePosition.js
import { ref, onMounted, onUnmounted } from "vue";

export function useMousePosition() {
  const x = ref(0);
  const y = ref(0);

  function update(e) { x.value = e.clientX; y.value = e.clientY; }

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

  return { x, y };
}

Expected output: Mouse position updates in real time and the sorted array displays alphabetically, both via composables.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro