Options API and Composition API
Vue.js offers two ways to write components: Options API and Composition API.
- Options API (Classic approach, uses
data,methods,computed,watch). - Composition API (More flexible, uses
setup(),ref(),reactive(),computed(),watch()).
Options API (Traditional Approach)
In Options API code is organized as object with options:
data— datamethods— methodscomputed— computed propertieswatch— watchersmounted,created— lifecycle hooks
Options API Example
<template>
<p>Counter: {{ count }}</p>
<button @click="increment">+</button>
</template>
<script>
export default {
data() {
return {
count: 0,
};
},
methods: {
increment() {
this.count++;
},
},
};
</script>
Options API Features
- Suitable for beginners
- Clearly separated sections (data, methods, computed)
- Can be complex for scaling
- Nested structures can worsen readability
Composition API (Modern Approach)
Composition API allows writing code inside setup(), using ref(), reactive(), computed(), watch.
Composition API Example
<template>
<p>Counter: {{ count }}</p>
<button @click="increment">+</button>
</template>
<script setup>
import { ref } from 'vue';
const count = ref(0);
const increment = () => count.value++;
</script>
Composition API Features
- Flexibility (can separate logic into functions)
- Code is cleaner and simpler
- Easier to reuse logic (through Composable functions)
- Requires getting used to
When to Use?
| Criterion | Options API | Composition API |
|---|---|---|
| Simple components | Yes | Yes |
| Large projects | Can be complex | Flexible |
| Reusable logic | Difficult | Convenient |
| Performance | Fast | Fast |
| Vue 2 support | Yes | Only via @vue/composition-api |
Summary
- Options API is good for simple components and beginners.
- Composition API — more scalable and convenient for large projects.