Home / Blog / Options API vs Composition API
Options API vs Composition API

Options API vs Composition API

Charles Allotey
Charles Allotey
January 26th 2023

The debate between the Options API and the Composition API in Vue.js has been a hot topic among developers since the release of the Composition API in Vue.js 3.0. Both approaches have their own unique benefits and drawbacks, and choosing the right one for your project can be a difficult decision.

In this article, we'll explore the differences between the two approaches and help you understand when to use each one.

First, let's define what each API is. The Options API is the traditional way of building Vue components, and it has been the primary method for building components in Vue since its inception. It involves using a set of options, such as data, methods, and computed properties, to define the behavior and state of a component.

<script>
export default {
    data() {
        return {
            name: '',
            age: 0,
            aboveAge:false
        }
    },
    computed: {
        displayProfile() {
         return `My name is ${this.name} and i am ${this.age}`;
        }
    },
    methods: {
         verifyUser() {
         if(this.age < 18){
         this.aboveAge = false
        } else {
        this.aboveAge = true    
           }
        },   
    },
    mounted() {
        console.log('Application mounted');
    },
}
</script>

On the other hand, the Composition API is a new way of building components in Vue 3.0 that was introduced to address some of the limitations of the Options API. It allows developers to use a functional, reactive programming style to build components, and it offers a more flexible and expressive way of defining component behavior.

<script setup>
import {ref, reactive, onMounted } from 'vue'

const profile = reactive({name:'', age:''})
const aboveAge = ref(false)

const verifyUser = () => age.value < 18 ? aboveAge = false : aboveAge = true

const displayProfile = computed(() => {
  return `My name is ${this.name} and i am ${this.age}`;
})

onMounted (() => console.log('Application mounted'))
</script>

Structure

One of the main benefits of the Options API is that it is simple and easy to understand. It follows a clear, declarative pattern that is familiar to many developers, and it is well-documented in the Vue documentation. This makes it a good choice for beginners who are just starting out with Vue.

However, the Options API has some limitations that can make it difficult to use for more complex projects. One issue is that it can become cumbersome to manage a large number of options as the complexity of a component increases. This can lead to a phenomenon known as "option explosion," where a component becomes so large and unwieldy that it is difficult to maintain.

Reusability

Another limitation of the Options API is that it can be inflexible when it comes to sharing logic between components. If you want to reuse a piece of logic across multiple components, you need to either copy and paste the code or abstract it into a mixin. This can make it difficult to manage code dependencies and maintain code quality as the size of a project grows.

var myMixin = {
  created: function () {
    this.hello()
  },
  methods: {
    hello: function () {
      console.log('hello from mixin!')
    }
  }
}

// define a component that uses this mixin
var Component = Vue.extend({
  mixins: [myMixin]
})

var component = new Component() // => "hello from mixin!"

The Composition API addresses these issues by providing a more flexible and expressive way of defining component behavior through composables. It allows developers to use a functional, reactive programming style to build components, which makes it easier to reuse logic and manage code dependencies.

// mouse.js
import { ref, onMounted, onUnmounted } from 'vue'

export function useMouse() {
  // state encapsulated and managed by the composable
  const x = ref(0)
  const y = ref(0)

  function update(event) {
    x.value = event.pageX
    y.value = event.pageY
  }

  onMounted(() => window.addEventListener('mousemove', update))
  onUnmounted(() => window.removeEventListener('mousemove', update))

  // expose managed state as return value
  return { x, y }
}

//usage in component
<script setup>
import { useMouse } from './mouse.js'

const { x, y } = useMouse()
</script>

This makes it easier to share logic between components and manage code dependencies as the size of a project grows. It also makes it easier to test and debug code, as the reactive declarative compositions are isolated and easier to reason about. Read more about mixins vs composables with the composition API here.

Usage

Another superior quality of the Composition API is that it allows developers to use the full power of JavaScript to define component behavior. This makes it possible to use advanced features such as async/await, Promises, and even third-party libraries like RxJS to build components. This can make it easier to build complex, interactive components that would be difficult or impossible to build with the Options API.

Learning

The Composition API may seem like the best options to use. However, the Composition API is not without its drawbacks. One issue is that it can be more difficult to learn for developers who are not familiar with functional, reactive programming. It also has a steeper learning curve than the Options API, which can make it a less appealing choice for beginners.

Compatibility

Another issue is that the Composition API is not backwards compatible with Vue 2.6 and under by default. This means that if you are using Vue.js 2.6 and under in an existing project, you will need to either upgrade to Vue 3.0 or import the Composition API via a plugin. But recently Vue.js announced that this plugin will reach its end of life by December 2022. This can be a significant when you have a large project built in Vue 2.6 and under.

Bundle Size

Code written in Composition API is also more efficient and minifiable than code written in Options API. This is because the template in a component is built as a function inlined in the same scope as the code. Unlike property access from this, the produced template code may directly access variables specified inside without the need for an instance proxy. This also improves minification because all variable names may be securely reduced.

Conclusion

Hope you enjoyed reading this article on Compostion API vs Options API. In this article, we compared and contrasted the Composition API and Options API and laid out the pros and cons of each. This should help you make an informed decision about which API to utilize in your next project.

But if you’re brand new to Vue.js we suggest you still start with the options API for it’s ease of use. Once you’ve got the options API down, it’ll be fairly straightforward to learn the composition API. If you’re already familiar with the options API, it’s definitely time to start learning the Composition API. Many new libraries, tutorials, and so on give heavy attention to the Composition API. You’ll be able to get more from these resources if you’re on top of the new syntax.

If you’re interested in learning more about either API, we’d encourage you to check out our extensive online courses on the Options API and Composition API. A very good and practical resource to understanding both APIs.

Related Courses

Start learning Vue.js for free

Charles Allotey
Charles Allotey
Charles is a Frontend Developer at Vueschool. Has a passion for building great experiences and products using Vue.js and Nuxt.

Latest Vue School Articles

Real-time data with Laravel Reverb and Vue.js

Real-time data with Laravel Reverb and Vue.js

Ready to unlock the potential of real-time data? Enroll in "Real-Time Data with Laravel Reverb and Vue.js" today and watch your applications come alive!
Daniel Kelly
Daniel Kelly
How to Master Vue Router in Vue.js 3 with Composition API

How to Master Vue Router in Vue.js 3 with Composition API

Discover how to effectively master Vue Router in Vue.js 3 using the powerful Composition API. This comprehensive guide provides step-by-step instructions, best practices, and practical examples to help you seamlessly integrate routing into your Vue.js projects.
Mostafa Said
Mostafa Said

Our goal is to be the number one source of Vue.js knowledge for all skill levels. We offer the knowledge of our industry leaders through awesome video courses for a ridiculously low price.

More than 120.000 users have already joined us. You are welcome too!

Follow us on Social

© All rights reserved. Made with ❤️ by BitterBrains, Inc.