✌️ Vue Options API To Composition API Migration Cheat Sheet

Tom Smykowski
3 min readJan 23

Below is a cheat sheet to move easily from Options API to Composition API in Vue. First script is “before”, and second: “after”:

Script

<script lang="ts">
export default {
data() {
return {
showHeaderMenu: false,
}
},
methods() {
toggleHeaderMenu() {
this.showHeaderMenu =
!this.showHeaderMenu;
},
}
}
</script>
<script setup lang="ts">

const showHeaderMenu = ref(false);

const toggleHeaderMenu = () => {
showHeaderMenu.value =
!showHeaderMenu.value;
};

</script>

You should have one <script> in your component with setup keyword

You don’t use export default and an object anymore, but rather write code line after line.

Props

props: {
icon: String,
name: String
}

this.name = 'something';
const props = defineProps({
icon: String,
name: String
});

props.name = 'something';

Instead of referencing this, you reference props now.

Emits

emits: {
close(accepted: boolean) {
return true;
}
},

this.$emit('close', saveChanges);
const emit = defineEmits({
close(accepted: boolean) {
return true;
}
});

emit('close', saveChanges);

Data

data() {
return {
showHeaderMenu: false,
}
},

this.showHeaderMenu =
!this.showHeaderMenu;
import { ref } from 'vue';

const showHeaderMenu = ref(false);

showHeaderMenu.value =
!showHeaderMenu.value;

<template>
<HeaderMenu
:show="showHeaderMenu"
/>
</template>

You don’t reference this to access state properties anymore

You use showHeaderMenu in template, but read and assign to showHeaderMenu.value in the script

For primitives and arrays use ref hook. For objects use reactive hook

Methods

toggleHeaderMenu() {
this.showHeaderMenu =
!this.showHeaderMenu;
},
const toggleHeaderMenu = () => {
showHeaderMenu.value =
!showHeaderMenu.value;
};
Tom Smykowski

Subscribe To Stay Up To Date With Software Engineering. Business queries: contact@tomasz-smykowski.com