Options vs Composition API
Vue offers two ways to organise a component: the Options API with named sections, and the Composition API with functions.
In this page:
Syntax
// Options API
export default {
data() { return { count: 0 }; },
methods: { increment() { this.count++; } }
}
// Composition API
setup() {
const count = ref(0);
return { count };
}
Options vs Composition API
The Options API groups code by option type (data, methods, computed). The Composition API groups it by feature inside setup, using ref, computed and friends, which makes logic easier to reuse. Both work in Vue 3 and can produce identical behaviour.
Note:
You can mix both styles in one project.
Example: Options vs Composition API
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<div id="app">
<options-counter></options-counter>
<composition-counter></composition-counter>
</div>
<script>
const app = Vue.createApp({});
app.component("options-counter", {
data() { return { n: 1 }; },
computed: { double() { return this.n * 2; } },
template: "<p>Options: {{ n }} x2 = {{ double }}</p>",
});
app.component("composition-counter", {
setup() {
const n = Vue.ref(1);
const double = Vue.computed(() => n.value * 2);
return { n, double };
},
template: "<p>Composition: {{ n }} x2 = {{ double }}</p>",
});
app.mount("#app");
</script>
</body>
</html>
<!-- Output:
Rendered: Options: 1 x2 = 2Composition: 1 x2 = 2
-->
Live Example
Related Topics
Common Mistakes
- Thinking one API is deprecated
- Mixing this and setup variables incorrectly
- Forgetting to return values from setup
Chapter Summary
- Options API: data, methods, computed
- Composition API: setup with ref and computed
- Both are supported in Vue 3
- Composition API helps reuse logic
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: