🎓 A1Learner
🔍
0 of 50 lessons completed

Composition API Introduction

The Composition API is the Vue style of building logic from small functions. It groups related logic in plain functions inside setup.

A ref and a computed value

doubled derives from count with a small function.

const count = ref(2)
const doubled = computed(() => count.value * 2)

The doubled value

count is 2, so doubled is 4.

<p>Doubled: {{ doubled }}</p>

Example

<script setup>
import { ref, computed } from 'vue'
const count = ref(2)
const doubled = computed(() => count.value * 2)
</script>
<template>
  <div>
    <p>Count: {{ count }}</p>
    <p>Doubled: {{ doubled }}</p>
  </div>
</template>

Key points

  • Composition API code lives in script setup, with functions like ref and computed.
  • A ref holds one changing value, and a computed value derives from it.
  • Related logic sits together in one place, even when it touches several values.
  • The same logic can move into its own function and be reused.
  • The template reads the refs and computed values like any other bindings.

In this example, count is a ref with the value 2. doubled is a computed value that doubles count. The template shows both values. The render shows Count 2 and Doubled 4. The logic is small and grouped, and the next lesson moves logic like this into its own function.

Note

Everything so far in this course already uses the Composition API.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What is the Composition API?