Vue3 Options vs Composition API

Vue3 Options vs Composition API

This article presents code snippets illustrating how to transition from the Options API to the Composition API in Vue 3.

Data

With the options API, reactive variables are defined in data():

<template>
  <p>x: {{ x }}</p>
</template>
<script>
export default {
  data() {
    return {
      x: 2,
    };
  },
};
</script>

Using the composition API, reactive variables are defined as refs:

<template>
  <p>x: {{ x }}</p>
</template>
<script setup>
import { ref } from "vue";
const x = ref(2);
</script>

Methods

When using the options API, methods are written in the property of the same name:

<template>
  <button @click="logX()">logX</button>
</template>

<script>
export default {
  data() {
    return {
      x: 2,
    };
  },
  methods: {
    logX(){
      console.log(this.x)
    }
  }
};
</script>

Whereas with the composition API, those can be defined as simple JavaScript functions:

<template>
  <button @click="logX()">logX</button>
</template>

<script>
import { ref } from "vue";
const x = ref(2);
function logX(){
  console.log(x.value)
}
</script>

Note that this.x becomes x.value

Computed

Computed properties with the options API:

<template>
  <p>x: {{ x }}</p>
  <p>x + 2: {{ xPlusTwo }}</p>
</template>
<script>
export default {
  data() {
    return {
      x: 2,
    };
  },
  computed: {
    xPlusTwo() {
      return this.x + 2;
    },
  },
};
</script>

And with the Composition API:

<template>
  <p>x: {{ x }}</p>
  <p>x + 2: {{ xPlusTwo }}</p>
</template>
<script setup>
import { ref, computed } from "vue";
const x = ref(2);
const xPlusTwo = computed(() => x.value + 2);
</script>

Mounted

Mounted used to be a method of the Vue component object:

<template>
  <p>x: {{ x }}</p>
</template>
<script>
export default {
  data() {
    return {
      x: 2,
    };
  },
  mounted(){
    this.x = 3
  }
};
</script>

With the composition API, it becomes a normal function with a callback:

<template>
  <p>x: {{ x }}</p>
</template>
<script>
import { ref, onMounted } from "vue";
const x = ref(2);
onMounted(() => {
  x.value = 3;
});
</script>

Final words

The composition API provides a syntax that is slightly more compact and closer to plain JavaScript than the options API. It also helps to better group to group pieces of code related to each other, which would originally be divided into data(), methods, and computed. This can be especially helpful for large and complex applications.