The Composition API and script setup
Why Vue 3 introduced the Composition API, how script setup works, and how it compares to the older Options API.
2 phút đọc
Vue 3 ships with two different styles for writing component logic: the Options API (Vue's original style, still fully supported) and the Composition API (introduced in Vue 3, now the recommended default). This course uses the Composition API with <script setup> throughout — this lesson explains why, and what the alternative looks like so you can recognize it in other code and tutorials.
The Options API, briefly
In the Options API, a component is an object with predefined option names — data, methods, computed — and Vue calls the right one at the right time:
<script>
export default {
data() {
return { count: 0 };
},
methods: {
increment() {
this.count++;
},
},
};
</script>
<template>
<button @click="increment">{{ count }}</button>
</template>This is organized by type of option, not by feature. In a small component that's fine. In a larger one with several unrelated pieces of state, each spread across data, computed, methods, and watch, understanding a single feature means jumping between four different sections of the file.
The Composition API
The Composition API instead lets you write plain JavaScript functions and variables, organized by feature rather than by option type:
<script setup>
import { ref, computed } from "vue";
const count = ref(0);
const doubled = computed(() => count.value * 2);
function increment() {
count.value++;
}
</script>
<template>
<button @click="increment">{{ count }} (doubled: {{ doubled }})</button>
</template>Everything related to the counter — its state, its derived value, its update logic — sits together, in whatever order makes sense to you. This also makes it far easier to extract reusable logic into standalone functions (called composables, covered later in this course) — something the Options API makes awkward.
What <script setup> adds
You could write the Composition API without <script setup>, using an explicit setup() function that returns everything the template needs. <script setup> is compile-time sugar that removes that boilerplate: every top-level binding — variables, functions, imports — is automatically exposed to the template, with no return statement and no export default needed.
<!-- Without script setup -->
<script>
import { ref } from "vue";
export default {
setup() {
const count = ref(0);
return { count };
},
};
</script>
<!-- With script setup — equivalent, less boilerplate -->
<script setup>
import { ref } from "vue";
const count = ref(0);
</script>Which one you'll see in the wild
Existing Vue 2 codebases and plenty of tutorials still use the Options API, so it's worth being able to read it. But for new code, <script setup> with the Composition API is what the Vue team recommends and what this course uses from here on — it's less verbose, composes better, and (for TypeScript users) infers types more reliably.