Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 87 ยท Lifecycle and Composition API

Composition API and script setup

Learn the Vue Composition API with setup() and script setup - what the template can see, how props and emits work, top-level await with Suspense, and how it compares to the Options API.

So far you have used ref, computed and watch inside a function called setup(). That function is the entry point of the Composition API, the style of writing Vue components where you organize code by what it does (a counter, a search filter, a timer) instead of by which option it belongs to (data, methods, computed). Everything you write in setup() is plain JavaScript, so it is easy to read, easy to move into a function and easy to reuse.

In real projects you will rarely type setup() by hand. Single-file components use a compile-time shortcut called <script setup>, which removes the boilerplate. This lesson explains both forms, shows exactly what the template can see in each, and tells you when each one is the right tool. The site's live examples cannot compile .vue files, so every SFC here is read-only and comes with a runnable setup() twin.

The setup() function

setup() is a component option. Vue calls it once per component instance, before the first render, and the object it returns becomes the data the template can use.

A component with a setup() function

Three things to notice. State is created with ref, so the script uses count.value while the template uses count (refs are unwrapped in templates, see Reactive state with ref). The function runs once, not on every update: it declares reactive state and wires it together, then Vue re-runs only the template when something changes. And nothing reaches the template unless you put it in the returned object.

flowchart LR
    A["createApp(component)"] --> B["setup() runs once<br/>declares refs, computed, functions"]
    B --> C["returned object<br/>becomes template scope"]
    C --> D["render function<br/>runs now and on every change"]

The setup function runs once; the render function runs again whenever a dependency changes.

What the template can see

With a plain setup(), the template can only use what you return. A local variable that is not returned simply does not exist for the template. Nothing is thrown, so the mistake is easy to miss.

Returned versus hidden bindings

The preview shows "shown: [I was returned]" and an empty pair of brackets for hidden. In the development build of Vue you would also see a console warning, Property "hidden" was accessed during render but is not defined on instance, but these examples load the production build, which stays silent. Forgetting to return a new function or ref is the most common setup() bug, and it is the first thing <script setup> removes.

script setup

Inside a .vue file, add the setup attribute to the script tag and write the body of setup() directly. Everything declared at the top level is automatically available to the template, and so is everything you import.

VUE
<script setup>
import { ref, computed } from "vue";
import UserBadge from "./UserBadge.vue";

const count = ref(0);
const double = computed(() => count.value * 2);

function increment() {
  count.value++;
}
</script>

<template>
  <UserBadge name="Ada" />
  <button type="button" @click="increment">
    Clicked {{ count }} times, double is {{ double }}
  </button>
</template>

This is the same component as the first example. Compare the two and count what disappeared: the setup() wrapper, the return statement, the component registration (components: { UserBadge }) and the options object. The Vue compiler reads the script, sees which names the template uses and generates the equivalent setup() for you. Your own code does not change, and you cannot forget to return something.

There are a few other differences worth knowing:

  • Imported components are used directly. UserBadge needs no registration. In the template you can write <UserBadge /> or <user-badge />.
  • The component is closed by default. A parent that holds a template ref to this component cannot read its variables. Use defineExpose to publish specific members (see Template refs and exposing methods).
  • Compiler macros need no import. defineProps, defineEmits, defineModel, defineExpose and defineOptions are replaced at compile time. They only work at the top level of <script setup>.
  • It is single-file only. <script setup> is a feature of the SFC compiler. In a template-string app like the examples on this site you write setup().

Read the rest of the file anatomy in Single-file components.

Think of <script setup> as setup() with the return written for you. If you understand the first form, you already understand the second.

Props and emits

A component also has to receive data and report events. In setup() the function takes two arguments: the reactive props object and a context with emit, attrs and slots. In <script setup> the two macros give you the same things.

VUE
<script setup>
const props = defineProps({ label: String, start: { type: Number, default: 0 } });
const emit = defineEmits(["change"]);

function report() {
  emit("change", props.start);
}
</script>
Props and emit through setup(props, context)

Press the buttons and the parent line updates: each component keeps its own value, and only the change event travels upward. The names props and emit are the ones defineProps and defineEmits give you in <script setup>.

Do not destructure props in a plain setup() (const { label } = props): you would copy the value once and lose reactivity. Use toRefs(props) or read props.label inside computed and watchers. Since Vue 3.5, destructuring defineProps inside <script setup> is reactive, because the compiler rewrites it to props.label for you, but that is a compiler feature and not available in setup().

Top-level await and Suspense

A component can be asynchronous: it waits for something before it has anything to render. In <script setup> you simply write await at the top level. In plain setup() you mark the function async.

VUE
<script setup>
const response = await fetch("/api/profile");
const profile = await response.json();
</script>

An async component can only render inside a <Suspense> boundary. Suspense shows its #fallback slot until every async descendant is ready, then swaps in the real content.

An async setup() inside Suspense

For about 0.6 seconds the preview shows "Loading profile...", then "Hello, Ada Lovelace! (loaded 1 time)". The mechanism is that setup() returned a promise, so Vue held the component back and the fallback stayed on screen.

In a hand-written async setup(), anything registered after the first await (lifecycle hooks, watchers, provide) has lost its connection to the component. The <script setup> compiler restores that context for you after top-level await, which is a good reason to prefer it. Also remember that Suspense is still marked experimental in Vue's own documentation, so keep its use focused.

Composition API versus Options API

Both APIs build the same components on top of the same reactivity system. The Composition API is not a replacement that makes the Options API wrong; it solves different problems.

Concern Options API Composition API
Organizing code By option type (data, methods) By feature, side by side
Reusing logic Mixins (hard to trace) Composables (plain functions)
Access to state this.count count.value
TypeScript Works, this typing is indirect Natural, ordinary variables
Learning curve Gentle, fixed places for code Needs the ref mental model

The practical advice is simple. Use <script setup> for new components, because it is the most compact form and the best supported by tooling. Know the Options API well enough to read older code: The Options API covers it and shows how each option maps to a composition equivalent.

flowchart TB
    subgraph Options["Options API"]
      O1["data"]
      O2["methods"]
      O3["computed"]
      O4["mounted"]
    end
    subgraph Composition["script setup"]
      C1["ref / reactive"]
      C2["functions"]
      C3["computed()"]
      C4["onMounted()"]
    end
    O1 --> C1
    O2 --> C2
    O3 --> C3
    O4 --> C4

Each Options API block has a direct counterpart in the Composition API.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In a component that uses a plain setup() function, what decides whether the template can use a variable?

    The template can only see what setup() returns. A local variable that is not returned is undefined for the template, and only the development build warns about it.
  2. 2. How often does setup() run for one component instance?

    setup() runs once per instance. Vue re-runs the render function when reactive dependencies change, not setup().
  3. 3. What does <script setup> add compared with writing setup() by hand?

    The SFC compiler generates the setup() wrapper and the return statement, so top-level variables, functions and imported components are available in the template.
  4. 4. An async component (top-level await) must be rendered inside which built-in component?

    Suspense waits for async descendants and shows its fallback slot until they are ready.

Summary

  • The Composition API organizes component code by feature, using plain functions and reactive primitives.
  • setup() runs once per instance; its returned object is the template scope.
  • <script setup> is compile-time sugar: top-level bindings and imports are exposed automatically, and macros such as defineProps and defineEmits need no import.
  • Props arrive as a reactive object (or through defineProps); do not destructure them in plain setup().
  • Top-level await and async setup() need a <Suspense> boundary.
  • Prefer <script setup> for new code and keep the Options API in your toolbox for older projects.

Next, learn when Vue calls your code during a component's life: Lifecycle hooks.