Learn how to leverage Vue 3’s Composition API for more flexible, scalable, and maintainable web apps. Step-by-step code examples included.
Table of content
Vue 3 introduced the Composition API, a powerful new way to write scalable and maintainable components. If you’re coming from Vue 2 or are new to Vue, understanding the Composition API will supercharge your web development workflow! Let’s dive into the essentials with practical code examples.
Start a new Vue 3 project (if you haven’t already):
npm init vue@latest
cd my-vue-app
npm install
npm run dev
In a component, use the <script setup>
syntax (recommended):
<script setup>
import { ref } from 'vue';
const name = ref('Vue 3');
</script>
<template>
<h1>Hello, {{ name }}!</h1>
</template>
ref()
– Reactive Variables<script setup>
import { ref } from 'vue';
const count = ref(0);
function increment() {
count.value++;
}
</script>
<template>
<button @click="increment">Count: {{ count }}</button>
</template>
reactive()
– Reactive State Objects<script setup>
import { reactive } from 'vue';
const form = reactive({
email: '',
password: ''
});
</script>
computed()
– Derived Data<script setup>
import { ref, computed } from 'vue';
const a = ref(2);
const b = ref(3);
const sum = computed(() => a.value + b.value);
</script>
<template>
<p>Sum: {{ sum }}</p>
</template>
watch()
– React to Changes<script setup>
import { ref, watch } from 'vue';
const keyword = ref('');
watch(keyword, (newVal, oldVal) => {
console.log('Keyword changed from', oldVal, 'to', newVal);
});
</script>
// useCounter.js
import { ref } from 'vue';
export function useCounter() {
const count = ref(0);
function increment() { count.value++; }
function decrement() { count.value--; }
return { count, increment, decrement };
}
<script setup>
import { useCounter } from './useCounter.js';
const { count, increment, decrement } = useCounter();
</script>
<template>
<button @click="decrement">-</button>
{{ count }}
<button @click="increment">+</button>
</template>
You can freely combine Composition API with the traditional Options API if migrating legacy components.
export default {
setup() {
// Composition API logic here
},
data() {
// Options API data here
}
}
<script setup>
for simpler, cleaner componentsref
for primitives, reactive
for objects/arraysuse*
for convention and clarityThe Composition API in Vue 3 empowers you to build robust, testable, and flexible applications. Practice by refactoring an old component or building something new—you’ll quickly appreciate the benefits!