5 min read
•Question 2 of 37mediumWhat is the difference between Composition API and Options API?
Understanding the two ways to write Vue components.
What You'll Learn
- Options API syntax
- Composition API syntax
- When to use each
Options API
Traditional Vue 2 style with organized options.
code.txtVUE
<script>
export default {
data() {
return {
count: 0,
name: 'Vue'
}
},
computed: {
doubleCount() {
return this.count * 2
}
},
methods: {
increment() {
this.count++
}
},
mounted() {
console.log('Component mounted')
}
}
</script>Composition API
Vue 3 style with composable functions.
code.txtVUE
<script setup>
import { ref, computed, onMounted } from 'vue'
const count = ref(0)
const name = ref('Vue')
const doubleCount = computed(() => count.value * 2)
function increment() {
count.value++
}
onMounted(() => {
console.log('Component mounted')
})
</script>Comparison
| Aspect | Options API | Composition API |
|---|---|---|
| Organization | By option type | By logical concern |
| Reusability | Mixins | Composables |
| TypeScript | Limited | Excellent |
| Learning curve | Easier | Steeper |