Developer's Corner
January 23, 2023

Vue 3 Composition API: Basics and Patterns

Vue 3 Composition API: Basics and Patterns

Darkweb v2.0 public release is here

Lorem ipsum dolor sit amet, consectetur adipiscing elit lobortis arcu enim urna adipiscing praesent velit viverra sit semper lorem eu cursus vel hendrerit elementum morbi curabitur etiam nibh justo, lorem aliquet donec sed sit mi dignissim at ante massa mattis.

  1. Neque sodales ut etiam sit amet nisl purus non tellus orci ac auctor
  2. Adipiscing elit ut aliquam purus sit amet viverra suspendisse potent i
  3. Mauris commodo quis imperdiet massa tincidunt nunc pulvinar
  4. Adipiscing elit ut aliquam purus sit amet viverra suspendisse potenti

What has changed in our latest release?

Vitae congue eu consequat ac felis placerat vestibulum lectus mauris ultrices cursus sit amet dictum sit amet justo donec enim diam porttitor lacus luctus accumsan tortor posuere praesent tristique magna sit amet purus gravida quis blandit turpis.

All new features available for all public channel users

At risus viverra adipiscing at in tellus integer feugiat nisl pretium fusce id velit ut tortor sagittis orci a scelerisque purus semper eget at lectus urna duis convallis. porta nibh venenatis cras sed felis eget neque laoreet suspendisse interdum consectetur libero id faucibus nisl donec pretium vulputate sapien nec sagittis aliquam nunc lobortis mattis aliquam faucibus purus in.

  • Neque sodales ut etiam sit amet nisl purus non tellus orci ac auctor
  • Adipiscing elit ut aliquam purus sit amet viverra suspendisse potenti
  • Mauris commodo quis imperdiet massa tincidunt nunc pulvinar
  • Adipiscing elit ut aliquam purus sit amet viverra suspendisse potenti
Coding collaboration with over 200 users at once

Nisi quis eleifend quam adipiscing vitae aliquet bibendum enim facilisis gravida neque. Velit euismod in pellentesque massa placerat volutpat lacus laoreet non curabitur gravida odio aenean sed adipiscing diam donec adipiscing tristique risus. amet est placerat in egestas erat imperdiet sed euismod nisi.

“Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum”
Real-time code save every 0.1 seconds

Eget lorem dolor sed viverra ipsum nunc aliquet bibendum felis donec et odio pellentesque diam volutpat commodo sed egestas aliquam sem fringilla ut morbi tincidunt augue interdum velit euismod eu tincidunt tortor aliquam nulla facilisi aenean sed adipiscing diam donec adipiscing ut lectus arcu bibendum at varius vel pharetra nibh venenatis cras sed felis eget dolor cosnectur drolo.

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, reactive, 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 organized while using Composition API.

Conclusion

You can still use Options API; but for larger codebases, it’s best to use Composition APIs for all its advantages. For smaller projects or if your projects use 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 the long run.

Want to know more about our latest testnet features? Book a demo.

Book a Demo

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