Статьи

Что нового в Vue?

В октябре 2018 года команда React анонсировала новую важную функцию для React версии 16.8 — Hooks. Эта функция обеспечит возможность добавления состояния к компонентам на основе функций, что ранее было возможно только с компонентами на основе классов и имеющими недостатки для масштабируемости.

В течение нескольких часов создатель Vue и ведущий дизайнер Evan You взволнованно писали идеи о том, как можно реализовать Hooks для Vue. Он, очевидно, видел эту новую парадигму разработки компонентов как средство преодоления ограничений в дизайне Vue так же, как и в React. В течение нескольких дней Вы выпустили рабочий демонстрационный плагин «Vue Hooks».

В ближайшие месяцы стало ясно, что команда Vue была продана с идеей, что метод композиции Hooks станет будущим Vue. Демонстрация Vue Hooks превратилась в то, что сейчас называется API Vue Composition, и планируется в качестве ключевой функции предстоящего выпуска Vue 3.

В этом отчете я объясню мотивы и ключевые идеи нового API композиции Vue и предложу несколько причин, по которым вы можете захотеть принять его (поскольку это дополнительная функция), или же продолжите использовать классический API, основанный на опциях, который вы Познакомимся с Vue 1 и 2.

Нестабильные Начало

Эван. Вы представили новый API в июле 2019 года как «API функции». Это было объявлено через публичный RFC (запрос комментариев) в качестве предлагаемой функции Vue 3.

В то время как сообщество получило много положительных откликов, это объявление было не очень хорошо принято. В последующие дни на форумах, таких как Reddit и Hacker News, начался поток жарких дискуссий, разделяющих сообщество Vue.

Самый большой страх у многих пользователей был в том, что существующий API, который они знали и любили (и вложили в него немало средств), вскоре от них оторвется, что заставит их использовать нежелательный новый API.

Было также ясно, что большинство пользователей не видят ценности или нововведений в новом API и считают новый стиль кода уродливым и трудным для чтения. Это резко контрастировало с существующим API, который обычно считался очень простым для понимания, и во многих случаях это было основной причиной того, что пользователи в первую очередь перешли на Vue из Angular или React.

После этого шторма Эван и команда Vue подтвердили ранее заниженные гарантии того, что новый API является чисто аддитивным, а существующий API останется без изменений.

Эван также создал  сайт документации  для нового API, который более подробно объяснил решения, стоящие за ним.

Выпуск этой новой документации также совпал с переименованием функции в «Composition API».

Теперь, когда пыль осела и эмоции успокоились, кажется, что многие пользователи действительно восприимчивы к тому, что предлагает новый API.

Пределы существующего API

Чтобы понять мотивацию API композиции, нам нужно понять ключевое ограничение существующего API из Vue 1 и 2 (которое официально безымянно, но для ясности я буду называть его «API параметров»).

Варианты API, как следует из названия, организует код компонента на высоком уровне по  выбору . Например, компонент, как правило , включает в себя  datamethodsи  computed варианты, которые гнездо функциональности компонентов.

Например:

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

Несмотря на то, что эта простая организация делает Vue очень простым в освоении и изучении, в реальных проектах разработки, особенно крупных, эта организация становится более неработоспособной.

Причина в том, что когда мы смотрим на код, чтобы попытаться понять его, нас в основном интересует то, что он  делает, а  не то, что он  имеет .

Например, скажем, у нас был  ShoppingCart компонент с различными функциями, которые вы ожидаете найти на странице корзины электронной коммерции.

Одна функция «добавить товар в корзину» будет фрагментирована по нескольким различным опциям в компоненте, основанном на опциях. Реактивные данные будут жить в  data объекте,  addToCart метод будет жить в  methods объекте, а готовый к отображению объект будет жить в  computed объекте.

Эта фрагментированная организация будет такой же для любых других функций, включенных в этот компонент.

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

Как работает новый API

Первая ключевая идея составного API заключается в том, что он позволяет упорядочить логику компонента по  функциональности , другими словами, то, что делает компонент  .

Чтобы продолжить предыдущий пример, функции  ShoppingCart компонента будут организованы на высоком уровне, например:

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