0
0
Vueframework~5 mins

Options API vs Composition API decision in Vue

Choose your learning style9 modes available
Introduction

Vue offers two ways to write components: Options API and Composition API. Choosing between them helps you organize your code better and work more easily.

You want simple and clear code for small projects or beginners.
You need to reuse logic across components in a clean way.
You want better TypeScript support and more flexible code structure.
You are working on a large project with complex components.
You want to gradually migrate old Vue code to newer patterns.
Syntax
Vue
Options API:
export default {
  data() {
    return { count: 0 };
  },
  methods: {
    increment() {
      this.count++;
    }
  }
}

Composition API:
import { ref } from 'vue';
export default {
  setup() {
    const count = ref(0);
    function increment() {
      count.value++;
    }
    return { count, increment };
  }
}

The Options API groups code by options like data, methods, and computed.

The Composition API groups code by feature or logic using functions inside setup().

Examples
Options API example: data and methods are separate sections.
Vue
export default {
  data() {
    return { message: 'Hello' };
  },
  methods: {
    greet() {
      alert(this.message);
    }
  }
}
Composition API example: data and methods are together inside setup().
Vue
import { ref } from 'vue';
export default {
  setup() {
    const message = ref('Hello');
    function greet() {
      alert(message.value);
    }
    return { message, greet };
  }
}
Sample Program

This is a simple Vue component using the Composition API. It shows a count and a button to increase it. The count updates reactively when you click the button.

Vue
<template>
  <div>
    <p>Count: {{ count }}</p>
    <button @click="increment">Increment</button>
  </div>
</template>

<script setup>
import { ref } from 'vue';
const count = ref(0);
function increment() {
  count.value++;
}
</script>
OutputSuccess
Important Notes

The Options API is easier for beginners and small projects.

The Composition API is better for complex logic and code reuse.

You can mix both APIs in the same project if needed.

Summary

The Options API organizes code by options like data and methods.

The Composition API organizes code by logical features inside setup().

Choose based on project size, complexity, and your comfort with Vue.