Go to content
The Codest
  • About Us
    • Staff Augmentation
    • Project Development
    • Cloud Engineering
    • Quality Assurance
    • Web Development
  • Our Team
  • Case studies
    • Blog
    • Meetups
    • Webinars
    • Resources
Careers Get in touch
  • About Us
    • Staff Augmentation
    • Project Development
    • Cloud Engineering
    • Quality Assurance
    • Web Development
  • Our Team
  • Case studies
    • Blog
    • Meetups
    • Webinars
    • Resources
Careers Get in touch
2022-06-02
Software Development

Stop using Options API in Vue

Pawel Dlugosz

Stop using Options API in Vue - Image

Why you shouldn't be using Options API in Due? Find answer to this question in the following article and discover the benefits of Composition API.

Vue 3 introduced a new approach to creating components called Composition API. It is an alternative to the Options API. The Composition API is fully optional and you don't need to use it if you want to use Vue 3. However, it introduces some important improvements that make your work easier and improve the readability of the code.

Advantages of Composition API over Options API

1. Better code organization and readability.

The Composition API introduces a new method called setup. Inside it, you can create all the necessary elements of the component, such as: data, methods, computed properties, watchers. Thanks to this, you can keep the code clean by placing the logic responsible for a given feature in one place. In contrast, the Options API forced the scattering of the logic throughout the file. As a result, the code was not readable and required scrolling. In Composition API methods, watchers etc. no longer need to be grouped by type, you can put them as you see fit.

API Options and composition example

2. Extracting out and reusing logic.

The Composition API allows you to write reactive code anywhere. You can pull some reactive logic outside of the component. This type of code is called Composables. Composables can be imported into many components and allow you to encapsulate some logic and expose the necessary reactive elements.

// shopping-list.js
import { computed } from "vue";

export function useShoppingList(listId) {
  const products = shoppingList.getAllProducts(listId);
  const productsCount = computed(() => products.value.length);
  const deleteProduct = (productId) => shoppingList.deleteProduct(productId);

  return {
    products,
    productsCount,
    deleteProduct,
  };
}

// Component
import useSpoppingList from "@/composables/shopping-list.js";
export default {
  setup() {
    const { products, productsCount, deleteProduct } = useSpoppingList();
    return { products, productsCount, deleteProduct };
  },
};

3. Easily use constants and external resources in component.

In the Options API, to add e.g. a static list of items imported from another file, you need to add it to data() (which has a negative impact on performance) or add it to this in created(). Both ways are not very elegant. The Composition API and the new setup method come to the rescue, from which you can export not only reactive things but also constants and external dependencies.

import list from "./list.json";
export default {
  setup() {
    return { list };
  },
};
  1. You can even use the Composition API in Vue 2.

Thanks to the official @vue/composition-api plugin, you can use Composition API in Vue 2 as well.

How to use the new Composition API?

<h3>Setup method</h3>

setup() is a new method added in Vue 3 where you can put all the necessary items such as data objects, methods etc. From there you can return the elements you want to include in the template.

<template>
  <div>{{ count }}</div>
</template>
import { ref } from "vue";
export default {
  setup() {
    const count = ref(10);
    return { count };
  },
};

reactive()

To create a reactive object or array you have to create it with the reactive(defaultValue) method. You can pass the initial value of this object via a method argument. The method returns a proxy for this object, so when you make changes to it, Vue knows about them and can properly refresh the view.

Composition API

import { reactive } from "vue";
export default {
  setup() {
    const user = reactive({
      name: "John",
      role: "ADMIN",
    });
    return { user };
  },
};

Options API

export default {
  data() {
    return {
      user: {
        name: "John",
        role: "ADMIN",
      },
    };
  },
};

Reactive only works for object types (objects, arrays, and collection types such as Map and Set). It cannot hold primitive types such as string, number or boolean. So Vue also introduces ref().

ref()

To add reactivity to primitive elements you have to wrap them with ref().

Composition API

import { ref } from "vue";
export default {
  setup() {
    const count = ref(10);
    return { count };
  },
};

Options API

export default {
  data() {
    return {
      count: 10,
    };
  },
};

Modifying reactive objects

You can change values in objects from the reactive method directly, but to change primitive values you must use the .value field.

import { ref, reactive } from "vue";
export default {
  setup() {
    const user = reactive({
      name: "John",
    });
    user.name = "John Doe"; // Value change

    const count = ref(10);
    count.value = 20;  // Value change

    return {
      user,
      count,
    };
  },
};

You don't need to use the .value property in the template.

<div>{{ count }}</div>

Computed Properties

Computed properties can be easily created by passing a method as a parameter to the imported computed() method.

import { reactive, computed } from "vue";
export default {
  setup() {
    const list = reactive([
      "Item 1",
      "Item 2",
    ]);

    // Computed
    const isEmpty = computed(() => list.length === 0);

    return {
      list,
      isEmpty,
    };
  },
};

Methods

You can also nest methods in the setup method.

Composition API

import { ref } from "vue";
export default {
  setup() {
    const count = ref(10);

        // Method
    const increment = () => {
      count.value++;
    };

    return {
      count,
      increment,
    };
  },
};

Watchers

Watchers are created in a similar way to computed. However, remember to pass the proxy object, i.e. name, as in the example below, not the name.value value itself.

import { watch, ref } from "vue";
export default {
  setup() {
    const name = ref("John");
        // Watcher
    watch(name, (currentValue, oldValue) => {
      console.log(`Value changed from ${oldValue} to ${currentValue}`);
    });
    return { name };
  },
};

Summary

In this article, I have only given you the basics of the Composition API so that you have a general understanding of how it differs and what advantages it has compared to the Options API. The Composition API also provides alternatives to the rest of the component's elements, such as hooks, and introduces new methods, such as watchEffect. It is a good idea to read it in the official Vue 3 documentation.

cooperation banner

Related articles

Software Development

Hiring Internal vs. External Developers

Hiring internally or externally? It's an ultimate dilemma! Find out advantages of outsourcing or building an in-house team in the following article.

Grzegorz Rozmus
Software Development

Javascript Tools in Action

Discover some retrieving JavaScript tools to level up your programming game. Learn more about ESLint, Prettier and Husky!

Reda Salmi
Software Development

Nuxt 3 - a Popular Hybrid Vue Framework

Nuxt 3 is the next generation of the popular hybrid Vue framework, which allows us to use Vue for building server-side rendered applications. Beta version was launched on 12 October 2021, bringing into Nuxt Vue 3, a new intro...

Filip Tobiasz
Software Development

Pros and Cons of React

Why is it worth to use React? What advantages this JavaScript library has? To find out the answers dive into this article and discover the real benefits of using React.

Cezary Goralski
Software Development

The Comparison of The Champions: Angular vs Vue

Currently, there are a few frontend frameworks used commonly and constantly developed by its creators, each slightly different than the other. And yet, they may have something in common. Here is a comparison based on the...

Oliwia Oremek

Subscribe to our knowledge base and stay up to date on the expertise from industry.

About us

The Codest – International Tech Software Company with tech hubs in Poland.

    United Kingdom - Headquarters

  • Office 303B, 182-184 High Street North E6 2JA London, England

    Poland - Local Tech Hubs

  • Business Link High5ive, Pawia 9, 31-154 Kraków, Poland
  • Brain Embassy, Konstruktorska 11, 02-673 Warsaw, Poland
  • Aleja Grunwaldzka 472B, 80-309 Gdańsk, Poland

    The Codest

  • Home
  • About us
  • Services
  • Case studies
  • Know how
  • Careers

    Services

  • PHP development
  • Java development
  • Python development
  • Ruby on Rails development
  • React Developers
  • Vue Developers
  • TypeScript Developers
  • DevOps
  • QA Engineers

    Resources

  • What are top CTOs and CIOs Challenges? [2022 updated]
  • Facts and Myths about Cooperating with External Software Development Partner
  • From the USA to Europe: Why do American startups decide to relocate to Europe
  • Privacy policy
  • Website terms of use

Copyright © 2022 by The Codest. All rights reserved.

We use cookies on the site for marketing, analytical and statistical purposes. By continuing to use, without changing your privacy settings, our site, you consent to the storage of cookies in your browser. You can always change the cookie settings in your browser. You can find more information in our Privacy Policy.