Vue 3 Composition API: Basics and Patterns

This blog is a part of our “Engineering at Arcana” series, and is written by our Frontend Developer Shrinath Prabhu.

Vue 3 introduced Composition API which allows developers to write components in a better way. Using this API, developers can group the logical pieces of code together, which in turn helps write readable code.

Composition API is a built in feature in Vue 3 and is also available in Vue 2 via @vue/composition-api plugin.

Before Composition API was introduced, Vue 2 was using Options API. While developers can still use Options API in Vue 3, the problem with it is that one single topic would be fragmented across different options such as data() or props, certain methods, some lifecycle hooks (mounted(), created(), and more), and watchers (watch).

With Composition API, you can organise code into smaller logical pieces, group them together, and even reuse them when required.

Let’s see a basic example to understand the difference of coding structure between Options API and Composition API.

This is how our highly logical code looks like in the Options API:

Example 1 using Options API

Now the same code can have separation of logic in the Composition API and it’ll look something like this:

Example 1 using Composition API

Clearly the Composition API code looks a lot cleaner since it can have separation of logic.

The above code can be even more simplified by using the <script setup> syntax, which allows us to get rid of setup method and exports. The following example shows how our code will look like using <script setup>.

Example 1 using Composition API with <script setup>

The example became even cleaner since it got rid of the export statement, the setup method, and the return statement.

The above syntax is the recommended syntax to be used while using Composition API.

Code reuse with Composition functions

Now let us see how to do code reuse using Composition functions. Before Composition API was introduced, developers were using the concept of mixins. A mixin is just a simple javascript which contains some vue options with some reusable logic that can be reused across multiple components.

Let’s checkout how a mixin looks like.

Counter Mixin (counterMixin.js)

Now let us see how we can use this mixin into our code:

Using Counter Mixin in the component

Basically, we can use the mixins option of Vue to use all the mixins that we have created. Looks good right? But there are few problems with this approach.

  • Property name conflicts can occur as properties from each mixin are merged into the same component.
  • It isn’t necessarily apparent which properties came from which mixin if a component uses multiple mixins.
  • It’s impossible to pass parameters to the mixin to change its logic which drastically reduces its flexibility.

These problems can be addressed using Composition API. So let us look at the same example using Composition API.

Counter Composable (useCounter.js)

Now let us see how we can use this in our code.

Using useCounter composable in our component

As you can see, it solves the problems that we discussed above:

  • We no longer have property name conflicts since we can encapsulate methods in a single object. We can also create multiple objects of same type and each object will be responsible for maintaining its own state.
  • We have a clear understanding of which properties emerged from which composable even if the component uses multiple composables.
  • We can even pass the parameters to the composables.
  • As you can see, Composition API also eliminates the use of this keyword, so we can use arrow functions more effectively.

What does Composition APIs expose?

According to Vue’s official documentation, Composition API exposes the following APIs:

  • Reactivity API, e.g. ref() and reactive() that allow us to directly create reactive state, computed state, and watchers.
  • Lifecycle Hooks, e.g. onMounted() and onUnmounted() that allow us to programmatically hook into the component lifecycle.
  • Dependency Injection, i.e. provide() and inject() that allow us to leverage Vue's dependency injection system while using Reactivity APIs.

Advantages of Composition APIs

The major advantages of using Composition APIs according to Vue’s official documentation are:

  • Better logic reuse.
  • More flexible code organisation.
  • Better Type interface as Vue 3 is written in Typescript.
  • Smaller production bundle and less overhead.

Disadvantages of Composition APIs

Here are a few disadvantages of using Composition APIs.

  • A lot of Vue based frameworks such as Nuxt and Vuetify still rely on Options API and have no support for Composition API (at the time of writing this article). Though these frameworks have beta support and third party libraries for supporting Vue 3, they don’t have a stable release as of now. In such cases, it’s better to stick to Options API as it makes more sense.
  • There might be confusion between ref()and reactive(), and beginners especially might get confused about when to use those and how exactly those differ from each other.
  • There is no support for options such name and inheritAttrs in Composition API. The workaround for this is to create a new script tag that uses Options API and use these options if required.

First class Typescript support

As mentioned in the advantages, Vue 3 is written in Typescript and has first class support for Typescript. You can type check all the pieces of component, such as props, refs, reactives, computed, and emits using Composition API with Typescript. Moreover, Vue 3 has exposed all the required interfaces for using it with Typescript.

Learn more about the usage with Typescript here.

Options API vs Composition API

Following image is an example of a larger codebase that have multiple features in a component and different colours are used to indicate different logical pieces.

Comparison between Options API and Composition API (source: vuejs.org)

As you can see, the code looks more organised while using Composition API.

Conclusion

You can still use Options API; but for larger codebases, it’s best to use Composition APIs for all it’s advantages. For smaller projects or if your projects uses dependencies that use Vue 2 (e.g. Nuxt, Vuetify, etc), you can use Options API. You can even use Options API along with Composition API, but stick to Composition API wherever possible as it’ll help in long run.

About Arcana Network

Arcana is the Web3 Infra to manage your data layer. Web3 App and wallet developers use Arcana’s SDK to authenticate users by generating wallets with Social and Passwordless Auth, Store Encrypted Data, and Manage Access. Built for Ethereum and EVM based chains, with Arcana’s privacy stack, developers can build secure and privacy-preserving apps with a seamless user experience.

Arcana has raised 2.7Mn USD from some of the leading investors and founders in the ecosystem such as Balaji Srinivasan, Founders of Polygon, Woodstock, Republic Crypto, and Digital Currency Group.

Watch out for Arcana’s upcoming Testnet and Mainnet in 2022.

Official Links: Website | Telegram | TG Announcement | Twitter | Medium

--

--

--

Arcana is the Storage Layer of Ethereum. A privacy centric stack for DApps on EVM compatible chains. | We write about all things Decentralized and Web 3.0

Recommended from Medium

Fourplay — Elixir [2Rs]

Top 5 React Native Starter Kits

How to Use Environment Variables in Codesphere

https://youtu.be/kQa5jw_olI8

Let’s Clear Up the Most Confusing Thing in CSS

computer screen showing CSS

A Quick and Clean Way to Parse Strings

The TypeScript logo

EthereumJS Recap January 2019

Classes > JavaScript — 10

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Arcana Network

Arcana Network

The Storage Layer of Ethereum | We write about all things Decentralization and Web 3.0

More from Medium

Todo App using VueJS 3 Composition API and Tailwind CSS

Actual App Screenshot Showcase

How to filter todo items? Vue 3 Composition API

Create a Basic useFetch Hook in Vue.js

vue custom useFetch hook

Top Web Applications Created Using Vue.js Framework