Academind Logo

Composition API - Complete Introduction

Vue 3 added the brand-new Composition API as an optional (!) alternative to the existing Options API. Using the Composition API is very easy and it's impact can be tremendous!

Created by Maximilian Schwarzmüller

The Composition API is a 100% optional new feature, introduced by Vue 3. You can use the Composition API instead of the existing Options API to write Vue components.

Here's how code looks like when using the Options API:

<template>
<h2>{{ message }}</h2>
<button @click="changeMessage">Change Message</button>
</template>
<script>
export default {
data() {
return {
message: 'This works just fine!'
};
},
methods: {
changeMessage() {
this.message = 'The Composition API is just an alternative!';
}
}
}
</script>

When switching to the Composition API, this code would look like this:

<template>
<h2>{{ message }}</h2>
<button @click="changeMessage">Change Message</button>
</template>
<script>
import { ref } from 'vue';
export default {
setup() {
const message = ref('This works just fine!');
function changeMessage() {
message.value = 'The Composition API is just an alternative!';
}
return {
message,
changeMessage
};
}
}
</script>

Watch the video at the beginning of this page to get a thorough introduction to the Composition API and understand what's happening here.

Recommended Courses