{{announcement.body}}
{{announcement.title}}

What's New in Vue?

DZone 's Guide to

What's New in Vue?

Discover the motivations and key ideas of Vue's new Composition API and why you should adopt it

· Web Dev Zone ·
Free Resource

In October 2018, the React team announced a major new feature for React version 16.8 - Hooks. This feature would provide a way for state to be added to function-based components, something previously possible only with class-based components and carried drawbacks for scalability.

Within hours, Vue creator and lead designer Evan You was excitedly tweeting ideas for how Hooks might be implemented for Vue. He evidentally saw this new paradigm of component design as a means of overcoming limitations in Vue's design the same way it did for React. Within a few days days, a working "Vue Hooks" demo plugin was released by You.

In the coming months, it became clear that the Vue team was sold on the idea that the Hooks method of composition would be the future of Vue. The Vue Hooks demo evolved into what is now called the Vue Composition API, and is slated as a key feature of the upcoming Vue 3 release.

In this report, I'll be explaining the motivations and key ideas of Vue's new Composition API, and offering some reasons why you may want to adopt it (as it's an optional feature), or continue using the classic options-based API that you'll be familiar with from Vue 1 and 2.

Unsteady Beginnings

Evan You introduced the new API in July 2019 as the "Function API." It was announced via a public RFC (request for comments) as a proposed feature of Vue 3.

While there were many positive reactions from the community, the announcement was not unverisally well received. Over the following days, a torrent of heated discussion began on forums like Reddit and Hacker News, dividing the Vue community.

The biggest fear many users had was that the existing API they knew and loved (and had heavily invested in) would soon be torn away from them, forcing them to use the unwelcomed new API.

It was also clear that most users couldn't see the value or innovation in the new API, and regarded the new code style as ugly and hard to read. This came in stark contrast to the existing API, which has generally been considered very easy to understand, and, in many cases, was the key reason that users had migrated to Vue from Angular or React in the first place.

In the aftermath of this storm, Evan and the Vue team reiterated previously understated assurances that the new API is purely additive and the existing API would remain intact.

Evan also created a documentation site for the new API, which explained the design decisions behind it in more detail.

The release of this new documentation also coincided with the renaming of the feature to the "Composition API."

Now that the dust has settled and emotions have calmed, it seems like many users are actually receptive to what the new API offers.

Limits of the Existing API

In order to understand the motivation behind the Composition API, we need to understand a key limitation of the existing API from Vue 1 and 2 (which is officially nameless, but which I'll refer to as the "options API" for clarity).

The options API, as the name suggests, organizes component code at a high level by option. For example, a component will typically include datamethods, and computed options, which nest the component functionality.

For example:

export default {
  data: () => ({ 
    ... 
  }),
  computed: {
    ...
  },
  methods: {
    ...
  },
  ...
}

While this simple organization makes Vue very easy to pick up and learn, in real-life development projects, particularly large-scale ones, this organization becomes more unworkable.

The reason is that when we look at code to try and understand it, we are mainly interested in what it does not what it has.

For example, say we had a ShoppingCart component with various features you'd expect to find on an eCommerce cart page.

One feature, "add item to cart," would be fragmented over several different options in an options-based component. The reactive data would live in the data object, the addToCart method would live in the methods object, and the object ready for display would live in the computed object.

This fragmented organization would be the same for any other features this component included.

<template>
  <ul>
    <li v-for="item in formattedItems">
      ...
    </li>
  </ul>
</template>
<script>
export default {
  name: "shopping-cart",
  data: () => ({
    cart: []
  }),
  computed: {
    formattedItems() {
      ...
    }
  }
  methods: {
    addToCart() {
      ...
    }
  }
}
</script>

How the New API Works

The first key idea of the composition API is that it allows component logic to be organized by feature, in other words, what the component does.

To continue the previous example, the features of the ShoppingCart component would be organized at a high level like this:

export default {
  setup() { ... },
  useAddToCart() { ... },
  useRemoveFromCart() { ... },
  useEmptyCart() { ... }
  ...
}

(The use prefix on the method names is a useful convention that I won't explain here).

Components created like this don't need high-level options like datamethodscomputed etc., as these are declared and returned from within each feature's function.

Here's an example from the new API documentation to demonstrate this.

<template>
  <button @click="increment">
    Count is: {{ state.count }}, double is: {{ state.double }}
  </button>
</template>
<script>
import { reactive, computed } from 'vue'
export default {
  setup() {
    const state = reactive({
      count: 0,
      double: computed(() => state.count * 2)
    });
    function increment() {
      state.count++
    }
    return {
      state,
      increment
    }
  }
}
</script>

(Note that the template functionality is exactly the same with the new API; it's just the component definition that's different.)

Why You Might Use the Composition API

What follows are three reasons that you and your team might want to either adopt the new API in future projects or migrate to it in existing projects.

1. Ease of Maintenance for Complex Components

In large apps, components can end up with hundreds of lines of code. If you use the options API, the developer will have to scan up and down the component definition in order to understand the relationship between the different options and the code's logic.

The composition API, on the other hand, provides the different features in neatly organized, easily understandable chunks.

2. Reusability of Features

Given the way composition API logic is arranged, it's trivial to extract and share logic between other components. For example, you could easily put the useAddToCart function in it's own module file, and include that functionality in other components besides ShoppingCart.

This is in contrast to the options API, where features are fragmented across different parts of the component, making reusability much harder to achieve without messy code.

3. Compatibility With TypeScript

Vue's options API simply wasn't designed with type inference in mind, and that results in a lot of complexity when trying to make it work nicely with TypeScript.

In comparison, the composition API utilizes mostly plain variables and functions, which are naturally type friendly, allowing full type inference with little need for manual type hints.

Why You Might Continue to Use the Options API

While the composition API provides a clear set of benefits, these may not be applicable to every team or project. Here are three reasons why you may prefer to stick with the existing options API which will continue to be supported in Vue 3.

1. Shallow Learning Curve

While the composition API is optimal for understanding component logic, the options API is optimal for learning Vue quickly, as organizing code by option helps familiarize the developer with Vue's key concepts.

If your projects use the composition API exclusively, you may find team members who are new to Vue face a steeper learning curve.

2. Tersity of Syntax and Lack of Boilerplate

The composition API introduces more verbsoe syntax than the option-based API. For example, a variable holding Vue state is an object with a value property that needs to be accessed, e.g. cart.value as opposed to simply cart.

There is also additional boilerplate code required for composition API components, for example the setup function that's now required.

It's worth mentioning, though, that some of the additional boilerplate actually helps with comprehension of the component and could be considered as missing information from options-based components.

3. Satisfies Your Needs

For many developers, the composition API simply does not solve a problem they have. In the majority of cases, Vue projects don't involve components with hundreds of lines of code, don't require too much code to be reused, and don't use TypeScript.

In these cases, there's little in the way of tangible benefits that migrating to the new API would offer.

How Will the Composition API Affect Vue Adoption

Anyone in the front-end world will be aware that Vue has been far-and-away the most rapidly growing framework over the past year or two, recently becoming the top open source JavaScript framework on GitHub.

The reason for this meteoric rise is two fold - it's partly because of its powerful feature set, but also because of strong word-of-mouth due to its delightfully shallow learning curve.

In terms of powerful features, the new composition API can really only add more reasons for new companies to start using it, as it's optional.

However, the PR misstep of how the new API was introduced, and the shift in focus towards power users may have slightly taintened the conversation about Vue. Perhaps we'll see a slow down in adoption as a result.

When Can the Composition API Be Used?

As of this writing, Vue 3 has just been publicly released as "pre alpha," meaning you can install it, but the features are not yet complete. It seems likely that around Q2 2020 is when there will be an official release.

In the meantime, the pre alpha version is a great way to start experiementing with the powerful - albeit controversial - Composition API.

This article was originally published in our JavaScript Frameworks Trend Report. To read more articles like this, download the report today!


Read Today  

Topics:
webdev ,vue ,api

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}