Composition API: a Quick overVue

Rate this content
Bookmark

Composition API is one of the biggest new features in Vue 3. In this talk, I will explain what is it and how to use Composition API for code abstraction and reuse.

This talk has been presented at JSNation Live 2020, check out the latest edition of this JavaScript Conference.

FAQ

The Composition API in Vue 3 is a new feature that allows developers to encapsulate and reuse logic in a modular way. It provides a way to organize code by grouping related logic together, which makes it easier to manage and maintain.

No, you do not need to rewrite all your Vue 2 components to use the Composition API. The new Composition API is purely additive and can be used alongside the existing Options API.

The Composition API solves problems related to reusability and organization of code. It allows developers to compose reusable features and abstract them, making the code less fragmented and easier to maintain.

Mixins in Vue 2 are not very reusable, can be conflict-prone due to property name collisions, and make it hard to track the source of methods, especially when using multiple mixins in a component.

Scoped slots in Vue allow a child component to expose part of its scope, such as data and methods, to its content. This makes the child component act as a wrapper that performs operations and exposes data and methods to its content.

The Composition API makes plugin development in Vue 3 easier by allowing developers to export functions created in the plugin and use provide/inject within the Vue instance, avoiding the need to extend the Vue prototype.

You should consider using the Composition API when you have features that need to be abstracted and reused or when developing plugins. However, if your team is already accustomed to the Options API and you don't have reusable features, there's no need to switch immediately.

The 'setup' function in the Composition API is invoked before the created hook and allows you to access the things returned from it in both the templates and the Options API. It is essential for initializing reactive properties and methods in the Composition API.

In the Composition API, you should pass values as refs or computed properties if you need them to be reactive. Non-reactive values should be passed as plain values.

While an exact date has not been provided, the release candidate for Vue 3 is expected to be available very soon, according to the Vue.js core team.

Natalia Tepluhina
Natalia Tepluhina
28 min
18 Jun, 2021

Comments

Sign in or register to post your comment.
Video Summary and Transcription
The video introduces the Composition API in Vue 3, explaining its benefits for organizing and reusing component logic. Using the CatSplorer app as an example, the speaker shows how the current code is fragmented and difficult to maintain. The Composition API allows developers to combine logical code in one place, similar to React hooks, and create custom hooks for reusability. It also simplifies the development of Vue plugins by allowing functions to be exported and used within the Vue instance. The video demonstrates how to use the ref function to create searchQuery and searchResultsQuery objects, and how to abstract the logic of API calls with the runBreedSearch method. The Composition API is purely additive, so there's no need to rewrite existing components. The setup option allows access to returned values in both templates and the options API. The video also touches on alternatives offered by Vue 2 for logic reuse, such as mixins and scope slots, and highlights their limitations. Finally, the video emphasizes that the Composition API is ideal for abstracting and reusing logic, while the Options API may be sufficient for simpler use cases.

1. Introduction to Vue 3 Composition API

Short description:

Today we are going to speak about one important feature of Vue 3, which is a composition API. The new composition API is purely additive, so you won't need to rewrite all your components written with the Options API.

Hi everyone! Today we are going to speak about one important feature of Vue 3 will bring, which is a composition API. But before we start speaking about it, I want to give you an important warning. When we first introduced this new API, we made a huge mistake. We were speaking about deprecating some options from the old API and people understood it slightly differently than we want. You can see some quotes from Reddit saying like, do I need to write all my components to the new syntax? And I want to say, no, please don't be like this. The new composition API is purely additive. You won't need to write all your good components written with Options API to this new syntax.

2. The Need for a New Vue.js API

Short description:

After introducing myself as Natalia, a Vue.js core team member and front-end engineer at GitLab, I explained the need for a new API in Vue.js version 3. Using the example of CatSplorer, an app for searching and sorting cat breeds, I showed how the current code is fragmented and difficult to maintain. I then introduced mixings as a way to compose reusable features, but highlighted their limitations in terms of reusability and customization.

And after this warning, now I'm safe and I can introduce myself. My name is Natalia and I'm Vue.js core team member. I care mostly about Vue documentation. I work as a staff front end engineer at GitLab, and I'm also a Google Developer expert in web technologies.

So why do we need this new API? Is there anything we were really lacking in Vue.js version 2? Let's take a look at this small application. Please meet CatSplorer, an app to search and sort cat breeds. As you can see, we have two features here. First is searching. Second is sorting with different parameters.

In the application code, this will look like this. So, this code belongs to search. We have some part of the reactive state responsible for searching, and we have a method to run this search. And of course we have something for sorting. Again, we have some reactive data, and we have some computed properties to calculate these sorted results.

If we take a look at the component code, we will see how these two features are divided in it. So here is a code that belongs to search, and here is a code for sorting. And as you can see, the logic is pretty much fragmented here. Imagine I'm a developer who needs to fix the search, and I need to follow this logic and I will be jumping from data to method and vice versa. So do we have a way to compose this reusable features and abstract them somehow?

So the first option in the current API are mixings. Mixing is an object that can contain any set of component properties like data methods, computed lifecycle hooks. And when mixing is included into the component, these properties are mixed in with component properties. Sometimes component can override mixing properties if the there is a name collision. Sometimes they are merged together like in the case of lifecycle hooks. But basically you need to understand there's just mixing in properties from mixing to the components. So here is a mixing for the search, and here is a sorting mixing that includes only properties we need for sorting. And if we take a look at this, this is way less fragmented, right? And then we just include this mixing as a component at the bottom. But there are some problems about mixing. First of all, they're not really reusable. If you did pay attention to the search mixing, you saw this access call. So we are not able to customize our search.

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

Everything Beyond State Management in Stores with Pinia
Vue.js London Live 2021Vue.js London Live 2021
34 min
Everything Beyond State Management in Stores with Pinia
Top Content
State management is not limited to complex applications and transitioning to a store offers significant benefits. Pinia is a centralized state management solution compatible with Vue 2 and Vue 3, providing advanced devtools support and extensibility with plugins. The core API of Pinia is similar to Vuex, but with a less verbose version of stores and powerful plugins. Pinia allows for easy state inspection, error handling, and testing. It is recommended to create one file per store for better organization and Pinia offers a more efficient performance compared to V-rex.
Welcome to Nuxt 3
Vue.js London Live 2021Vue.js London Live 2021
29 min
Welcome to Nuxt 3
Top Content
Nux3 has made significant improvements in performance, output optimization, and serverless support. Nuxt Bridge brings the Nitro engine for enhanced performance and easier transition between Nuxt 2 and Nuxt Read. Nuxt 3 supports Webpack 5, Bytes, and Vue 3. NextLab has developed brand new websites using Docus technology. Nuxt.js is recommended for building apps faster and simpler, and Nuxt 2 should be used before migrating to Nuxt 3 for stability. DOCUS is a new project that combines Nuxt with additional features like content modules and an admin panel.
One Year Into Vue 3
Vue.js London Live 2021Vue.js London Live 2021
20 min
One Year Into Vue 3
Top Content
Vue 3 has seen significant adoption and improvements in performance, bundle size, architecture, and TypeScript integration. The ecosystem around Vue 3 is catching up, with new tools and frameworks being developed. The Vue.js.org documentation is undergoing a complete overhaul. PNIA is emerging as the go-to state management solution for Vue 3. The options API and composition API are both viable options in Vue 3, with the choice depending on factors such as complexity and familiarity with TypeScript. Vue 3 continues to support CDN installation and is recommended for new projects.
Utilising Rust from Vue with WebAssembly
Vue.js London Live 2021Vue.js London Live 2021
8 min
Utilising Rust from Vue with WebAssembly
Top Content
In this Talk, the speaker demonstrates how to use Rust with WebAssembly in a Vue.js project. They explain that WebAssembly is a binary format that allows for high-performance code and less memory usage in the browser. The speaker shows how to build a Rust example using the WasmPack tool and integrate it into a Vue template. They also demonstrate how to call Rust code from a Vue component and deploy the resulting package to npm for easy sharing and consumption.
Vue: Feature Updates
Vue.js London 2023Vue.js London 2023
44 min
Vue: Feature Updates
Top Content
Watch video: Vue: Feature Updates
The Talk discusses the recent feature updates in Vue 3.3, focusing on script setup and TypeScript support. It covers improvements in defining props using imported types and complex types support. The introduction of generic components and reworked signatures for defined components provides more flexibility and better type support. Other features include automatic inference of runtime props, improved define emits and defined slots, and experimental features like reactive props destructure and define model. The Talk also mentions future plans for Vue, including stabilizing suspense and enhancing computer invalidations.
Local State and Server Cache: Finding a Balance
Vue.js London Live 2021Vue.js London Live 2021
24 min
Local State and Server Cache: Finding a Balance
Top Content
This Talk discusses handling local state in software development, particularly when dealing with asynchronous behavior and API requests. It explores the challenges of managing global state and the need for actions when handling server data. The Talk also highlights the issue of fetching data not in Vuex and the challenges of keeping data up-to-date in Vuex. It mentions alternative tools like Apollo Client and React Query for handling local state. The Talk concludes with a discussion on GitLab going public and the celebration that followed.

Workshops on related topic

Vue3: Modern Frontend App Development
Vue.js London Live 2021Vue.js London Live 2021
169 min
Vue3: Modern Frontend App Development
Top Content
Featured WorkshopFree
Mikhail Kuznetsov
Mikhail Kuznetsov
The Vue3 has been released in mid-2020. Besides many improvements and optimizations, the main feature of Vue3 brings is the Composition API – a new way to write and reuse reactive code. Let's learn more about how to use Composition API efficiently.

Besides core Vue3 features we'll explain examples of how to use popular libraries with Vue3.

Table of contents:
- Introduction to Vue3
- Composition API
- Core libraries
- Vue3 ecosystem

Prerequisites:
IDE of choice (Inellij or VSC) installed
Nodejs + NPM
Monitoring 101 for React Developers
React Summit US 2023React Summit US 2023
107 min
Monitoring 101 for React Developers
Top Content
WorkshopFree
Lazar Nikolov
Sarah Guthals
2 authors
If finding errors in your frontend project is like searching for a needle in a code haystack, then Sentry error monitoring can be your metal detector. Learn the basics of error monitoring with Sentry. Whether you are running a React, Angular, Vue, or just “vanilla” JavaScript, see how Sentry can help you find the who, what, when and where behind errors in your frontend project. 
Workshop level: Intermediate
Using Nitro – Building an App with the Latest Nuxt Rendering Engine
Vue.js London Live 2021Vue.js London Live 2021
117 min
Using Nitro – Building an App with the Latest Nuxt Rendering Engine
Top Content
Workshop
Daniel Roe
Daniel Roe
We'll build a Nuxt project together from scratch using Nitro, the new Nuxt rendering engine, and Nuxt Bridge. We'll explore some of the ways that you can use and deploy Nitro, whilst building a application together with some of the real-world constraints you'd face when deploying an app for your enterprise. Along the way, fire your questions at me and I'll do my best to answer them.
Going on an adventure with Nuxt 3, Motion UI and Azure
JSNation 2022JSNation 2022
141 min
Going on an adventure with Nuxt 3, Motion UI and Azure
WorkshopFree
Melanie de Leeuw
Melanie de Leeuw
We love easily created and deployed web applications! So, let’s see what a very current tech stack like Nuxt 3, Motion UI and Azure Static Web Apps can do for us. It could very well be a golden trio in modern day web development. Or it could be a fire pit of bugs and errors. Either way it will be a learning adventure for us all. Nuxt 3 has been released just a few months ago, and we cannot wait any longer to explore its new features like its acceptance of Vue 3 and the Nitro Engine. We add a bit of pizzazz to our application with the Sass library Motion UI, because static design is out, and animations are in again.Our driving power of the stack will be Azure. Azure static web apps are new, close to production and a nifty and quick way for developers to deploy their websites. So of course, we must try this out.With some sprinkled Azure Functions on top, we will explore what web development in 2022 can do.
TresJS create 3D experiences declaratively with Vue Components
Vue.js London 2023Vue.js London 2023
137 min
TresJS create 3D experiences declaratively with Vue Components
Workshop
Alvaro Saburido
Alvaro Saburido
- Intro 3D - Intro WebGL- ThreeJS- Why TresJS- Installation or Stackblitz setup - Core Basics- Setting up the Canvas- Scene- Camera- Adding an object- Geometries- Arguments- Props- Slots- The Loop- UseRenderLoop composable- Before and After rendering callbacks- Basic Animations- Materials- Basic Material- Normal Material- Toon Material- Lambert Material- Standard and Physical Material- Metalness, roughness - Lights- AmbientLight- DirectionalLight- PointLights- Shadows- Textures- Loading textures with useTextures- Tips and tricks- Misc- Orbit Controls- Loading models with Cientos- Debugging your scene- Performance
Building Vue forms with VeeValidate
Vue.js London Live 2021Vue.js London Live 2021
176 min
Building Vue forms with VeeValidate
Workshop
Abdelrahman Awad
Abdelrahman Awad
In this workshop, you will learn how to use vee-validate to handle form validation, manage form values and handle submissions effectively. We will start from the basics with a simple login form all the way to using the composition API and building repeatable and multistep forms.

Table of contents:
- Introduction to vee-validate
- Building a basic form with vee-validate components
- Handling validation and form submissions
- Building validatable input components with the composition API
- Field Arrays and repeatable inputs
- Building a multistep form
Prerequisites:
VSCode setup and an empty Vite + Vue project.