Two Ways to Write a Component — Pick One
Options API vs Composition API
Vue 3 supports both APIs. New code defaults to the Composition API with `<script setup>`; the Options API remains for legacy code.
What you'll learn
- Recognize each style
- Know that `<script setup>` is the modern shorthand for Composition API
- See the conversion path
Vue 3 supports two styles for authoring a component: the older Options API (organize by option type) and the modern Composition API (organize by feature). Both compile to the same thing — but they read very differently.
Options API
<script>
export default {
data() {
return { count: 0 }
},
computed: {
doubled() { return this.count * 2 }
},
methods: {
inc() { this.count++ }
},
mounted() {
console.log('mounted')
},
}
</script> State, computed, and methods each live in dedicated blocks. this refers to the component.
Composition API
The Composition API uses standalone functions — ref, computed, onMounted — and groups logic by what it does.
<script setup>
import { ref, computed, onMounted } from 'vue'
const count = ref(0)
const doubled = computed(() => count.value * 2)
const inc = () => count.value++
onMounted(() => console.log('mounted'))
</script> <script setup> is sugar over the longer setup() function — top-level bindings are auto-exposed to the template.
Why the Composition API Won
- Logic reuse: extract
useFoo()composables that work in any component. - TypeScript: no
this-magic — types flow naturally. - Co-location: related code stays together rather than spread across
data,methods,computed.
Options API still works and will not be removed — feel free to keep legacy code. New code should default to Composition + <script setup>.