Composition API VS Options API in Vue 3 For Beginners

Robin
October 27, 2022

Up until Vue 3, we used to have one official way to create a Vue component which is known as Options API. But in Vue version 3, we got another way to do the same thing which is Composition API.

Composition API helps to organize Vue 3 components by grouping code together. Like Options API, we don't have to write code in different sections i.e. data, methods, computed, etc. It also allows us to reuse code in different components with composables.

Now the question is, why should you use Composition API over Options API?

It is not compulsory that you have to use Composition API in order to use Vue 3. It still supports Options API at its core. It is also possible to use both methods together in a single Vue component.

In this article, you will all about the differences between Composition API and Options API in detail so that you can choose the best option for your Vue application.

Also Read: Best Ways to Use v-model to Custom Components in Vue 3

Composition API VS Options API in Vue 3

Both APIs are alternatives to each other. You can also use them together if you want. But they are different in terms of their appearance.

For example, using Options API, it was difficult to organize your code inside your components. Because you had to separate your logic into multiple parts to make them work. Like, data, method, computed, etc.

Composition API

Now using Composition API, you can do all those things but in a lot more organized way which makes your code much cleaner and easy to manage.

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

const amount = ref(0);
const balance = ref(0);

const balanceString = computed(() => `Account Balance: ${balance.value}`);

const addBalance = () => {
    balance.value += amount.value;
    amount.value = 0;
}

const subtractBalance = () => {
    balance.value -= amount.value;
    amount.value = 0;
}

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

That is why nowadays most developers prefer Compositions API over Options API. But to understand their benefits and drawbacks you must know the differences between them.

Options API

In Options API, we were limited to an object to configure a component with properties and methods. But in Compositions API, we use different hooks to do the same things.

          <script>
export default {
    data() {
        return {
            balance: 0,
            amount: 0
        }
    },
    computed: {
        balanceString() {
            return `Account Balance: ${this.balance}`;
        }
    },
    methods: {
        addBalance() {
            this.balance += this.amount
            this.amount = 0;
        },
        subtractBalance() {
            this.balance -= this.amount
            this.amount = 0;
        }
    },
    mounted() {
        console.log('Application mounted');
    },
}
</script>
        

This feature gives us complete control over our code. You can organize your code, however, your want.

Compositions API solves 2 major limitations that Options API had:

  • Group relevant pieces of code together using hooks.
  • Helps to reuse code throughout your application very easily using composable.

Let's see the differences between composition API and options API in Vue 3 components.

Also Read: Add Active & Exact Active Class to <router-link> in Vue 3

Group and Organize Codes with Composition API

I mentioned earlier that Composition API solves 2 major limitations that Options API has. This is one of them. It is very difficult to organize related codes together in Options API. Because we have to put our code in a specific section to make them work.

For example, if you have two methods one for users and another for products, you have to put both of them together inside the methods property even though they are not related to each other.

If you have two computed properties for users and products, you have to put them together inside the computed property.

So, you can see what is happening. Computed property and method for users are in different sections even though they are related.

This is the problem Composition API solves.

Composition API VS Options API in Vue 3 For Beginners

In the above picture, you can see that in Options API everything is scattered in data(), computed, methods, watch, and lifecycle methods.

It might look simple but imagine you have 100 components like this in your application. It becomes very painful and difficult to handle when you try to modify or add new features.

On the other side, you can see in Compositions API I have grouped all related codes together into 3 sections. The first section works with personal details like name and age.

The second section handles everything about the users. And the third section contains all the lifecycle hooks.

Now If you want to modify or add something to this component you just know where to look. Because everything is so organized and clean.

Also Read: Improve Performance in Vue 3 Using Lazy Loading and Dynamic Import

Better Code Reusability Using Composables

Sharing code among multiple components was very difficult in Options API. This is another major limitation that Composition API solves.

Now you can easily reuse your code in multiple components using hooks. So you don't have to write the same code in multiple components.

          // src/composables/user-list.js

import { computed, ref } from 'vue';

export const useUserList = () => {
    const users = ref(['Jane', 'Mark', 'Bob']);
    const usersList = computed(() => users.value.join(', '));
    const addUser = (user) => {
        users.value.push(user);
    };
    const removeUser = (username) => {
        users.value = users.value.filter((user) => user !== username);
    };

    return {
        users,
        usersList,
        addUser,
        removeUser,
    };
};

        
          <script setup>
import { useUserList } from '@/composables/user-list';

const { users, usersList, addUser, removeUser } = useUserList();

</script>
        

You can share your code among multiple components by creating composable. It is a simple function that will return all the necessary data, computed, or methods.

Here, I have created useUserList() function that returns user, usersList, addUser(), and removeUser(). Now all I have to do is import this function in any component.

As I am using ref() and computed() in my function, all this data will be reactive. When I add or remove any user all the components that are using this composable function, will update automatically.

Now I can reuse this function again and again without repeating the same code in different places.

Passing Constants and Dependencies in The Template

If you want to pass a constant value to your <template> in Options API, you have to add that value to the data option. Everything you add in the data option will be reactive.

Even though the constant value will never change, you need to define it as a reactive property in the Options API. Otherwise, that value isn't available in your Vue template.

It also has a performance overhead. Because Vue always keeps track of the reactive properties. In this case, Vue will track a value that never changes.

          <template>
    <div>
        <!-- ... -->
        <input type="text" v-model="username" placeholder="Enter Username" />
        <span>Minimun length is {{ MIN_LENGTH }}</span>
    </div>
</template>

<script setup>
import { ref } from 'vue';

const MIN_LENGTH = 8;

const username = ref('');
</script>
        

But composition API can solve this issue very easily. We use ref() to create reactive properties. When we create a regular variable inside the setup() function, it will not be reactive and Vue won't track the changes.

Here, you can access MIN_LENGTH variable inside the <template> section. Vue will not track this variable. On the other hand, the username variable is reactive.

Also Read: Context Argument in Vue 3 Composition API Script Setup

What Makes the Composition API Better than the Options API?

After you know the differences between Composition API and Options API, you can identify the places where Composition API provides better value.

More and more developers are adopting Composition API because of its new features and ease of use.

As a developer, I always prefer using Composition API over Options API. There are many reasons for that:

  • It helps to write clean code.
  • It makes our code look very simple and easily readable.
  • You can effortlessly update or add new features to your application.
  • You can organize your component into different sections with related codes.
  • You can create a composable function to reuse your code among different components.

Using the Composition API with Vue 2

After knowing all these new features, you might want to use Composition API in your application. But Composition API is added to Vue 3 by default.

If you are using Vue 2 then you have two options. You can migrate your app from Vue 2 to Vue 3. But if you can not do it at this moment for any reason, you still can use the new Composition API features by adding the official Composition API for Vue 2 plugin.

Conclusion

In this article, I have tried to give you all the major differences between Composition API and Options API. I hope after reading this, you got a clear picture of them.

When you know the differences, it becomes very easy to choose the right option. I tried to show you the advantages that you will get by using Composition API.

Now you know everything about Composition API Vs Options API in detail. You can select one of them according to your need.

Related Posts