Options API vs Composition API: Choosing the Right Approach for Your Team

Rate this content
Bookmark

With the introduction of Composition API into the Vue ecosystem, many are curious as to what they should pick. Options API? Composition API? Which is best? What are the tradeoffs? In this talk, we'll examine the two approaches so that you can make the right decision for your app.

This talk has been presented at Vue.js London Live 2021, check out the latest edition of this Tech Conference.

FAQ

The Options API in Vue is highly structured, providing specific places for code such as data, computed properties, and methods, making it easy to learn but less flexible. The Composition API, introduced in Vue 3, offers more flexibility by allowing developers to use plain JavaScript, organize code as they prefer, and is more TypeScript friendly, but it has a higher learning curve and less inherent structure.

The new script setup syntax in Vue 3 simplifies the Composition API usage by removing the need to export an object and manually define setup methods. It automatically detects what should be exposed to the component, leading to cleaner and more concise code.

Yes, Vue allows for a hybrid approach where both Options API and Composition API can be used together. This approach allows developers to leverage the structured nature of Options API while incorporating the flexibility of the Composition API, suitable for progressively enhancing existing codebases.

The Options API is easy to understand and learn, especially for beginners or those not deeply familiar with JavaScript. It offers a highly structured codebase where components have a consistent format, making them predictable and easier to manage.

While the Composition API provides greater flexibility and is more friendly towards TypeScript, it can lead to potential anti-patterns due to its less structured nature. This flexibility requires developers to maintain best practices actively to avoid scalability issues in large projects.

The script setup syntax streamlines component setup by removing repetitive configurations and automatically handling the exposure of variables and methods to the template. This results in a more intuitive and less verbose coding experience, especially beneficial when using the Composition API.

When deciding between Options API and Composition API, consider the existing codebase, the JavaScript proficiency of the team, the project's requirements for TypeScript, and team preferences. The choice should align with the team's skills and the project's needs to optimize development efficiency and maintainability.

Ben Hong
Ben Hong
23 min
21 Oct, 2021

Comments

Sign in or register to post your comment.

Video Summary and Transcription

Today's Talk discusses the Options API and Composition API in Vue 3, highlighting the differences and considerations when choosing an approach. The Composition API offers more flexibility and integrates well with TypeScript, but may require more familiarity with JavaScript. Combining both APIs allows for structure and flexibility, with the ability to progressively enhance code. Team preferences and the level of TypeScript usage should be considered when choosing the right approach for a project.

1. Introduction to Options API and Composition API

Short description:

Today we're here to talk about both Options API and Composition API and how to choose the right approach for your team. I'm a staff developer experience engineer at Netlify, on the Vue core team, a Nuxt ambassador, Vue mastery instructor, and a Google developer expert. Before Vue 3, things were simpler with the Options API. With Vue 3's Composition API, it got more complicated. The Composition API uses the Setup method and provides a different way to structure data and methods.

What's up Vue London? How's it going? I'm excited today because I'm here to talk about something that, well, has been discussed quite a bit within the Vue community, and that's the whole idea between whether or not to use Options API or Composition API. So today we're here to talk about both and how to choose the right approach for your team.

For those who don't know me, my name is Ben Hong and you can find me under the Internet of Things under the username BenCodeZen. A little bit about me if you haven't encountered my work before. I'm a staff developer experience engineer at Netlify. I'm on the Vue core team spending most of my time primarily on docs as well as community-related activities and then I'm also a Nuxt ambassador which again if you haven't heard, very excited because Nuxt public beta is now out, so be sure to check that out. I'm also a Vue mastery instructor and a Google developer expert in web technologies and matplatform.

All right, so to kick things off let's face it, before vue 3s things were well simpler. Simpler how so? Well because there was only one way to write our components, so in other words this is what we have basically come to know as the options API. And so just to make sure we're all on the same page, here we have a component here that contains your standard Options API things. So what you have here at the very top here is a script block and then inside of here we're exporting a default object and then we have things like your data, your computed properties, as well as the methods that you're calling inside of this template which goes ahead and renders those things out or calls the appropriate methods. And so hence since we have these opinionated places for where you put your code, i.e. data, computed methods, this was the Options API. Well, with Vue 3 introducing the Composition API though, well it got a little bit more complicated because now let's go ahead and just, just in case people don't know what the Composition API is, let's do a quick overview of the difference. So here in our Options API we have very opinionated ways of how we put our data. Well the first thing you can tell when it comes to the Options API, or sorry, the first thing you can tell when it comes to the Composition API is that we're using the Setup method. So we'll shift everything down, you'll see that this setup function inside of our exported object. And inside of here what we're going to do, let's start moving things in to show you what it looks like in Composition API. So the first thing first is we'll take the data, the count property of zero, and we'll move that up and declare that with a const of count zero. And then we'll need to make that reactive for Vue to track that. So we'll go ahead and import the ref which makes it a reactive reference. And we wrap the value zero in it. And so now that count is basically a reactive reference of zero. And then computed becomes something that we can actually use as like a helper method similar to ref. So we'll import it here. And then what it similarly does is we declare a variable of double count, and it returns the count value the reactive reference times two. So it acts exactly the same way. And then finally, our methods here increment count. Again, just like normal JavaScript here, const increment count, it is a function. And what does it do? It increments the value of count plus plus.

2. Introduction to Script Setup and Options API

Short description:

Now we won't get into the details and sort of how ref and all this stuff works. But here you have a kind of high level of sort of a one to one of what happens when these things get moved into composition API. And because we're in the setup method of having everything exported at this point. One more piece that we need to have is we need to actually explicitly tell view, basically what we want to actually expose to the component, because sometimes certain things are more call it like private methods or private variables. And these are things that we want to expose to the template. And so we turn an object very similarly to the data property. For those of you who've been following closely, well, View 3.2 released yet another way to write components, although another should be put in quotes, because really it's a sort of an enhancement on as far as the developer experience on top of the composition API, and that is the new script setup syntax. And so let's talk about the three different approaches that I would say generally people have to choose between when it comes to this. The first of which is just pure options API. It's very easy to learn and provides a sense of consistency amongst the components. However, it is also opinionated.

Now we won't get into the details and sort of how ref and all this stuff works. But here you have a kind of high level of sort of a one to one of what happens when these things get moved into composition API. And because we're in the setup method of having everything exported at this point. One more piece that we need to have is we need to actually explicitly tell view, basically what we want to actually expose to the component, because sometimes certain things are more call it like private methods or private variables. And these are things that we want to expose to the template. And so we turn an object very similarly to the data property.

And so for those of you who've been following closely, well, View 3.2 released yet another way to write components, although another should be put in quotes, because really it's a sort of an enhancement on as far as the developer experience on top of the composition API, and that is the new script setup syntax. So let's do a quick review on that. And so back inside of our basically our counter example, we can see here that we have the composition API method that we had basically shown the transition of earlier that we migrated from options. Let's go ahead and show you what script setup looks like. So the first thing first is that we're gonna get rid of the exporting object, because what script setup does really it says we're going to assume you only want to use composition API, so we're not going to export an object. And more importantly, we know you're going to set up methods. So why make you define that again? So we're going to do is we're going to move that setup method and move it as an attribute as a script setup. Specifically set up is an attributable script, and then as a result, the compiler knows to do special things with the code inside. So now that we have script setup, though, we also know. Well, we can also do some sort of auto detection of what you probably want to expose to the component. So actually what we get to do as well is we get to remove the manual exposing of variables, which is quite nice. And so you get this code that's quite clean, easy to understand. And then here as a result, you have a pure composition API using the script setup. Basically, the developer experience improvement. Of course, some of you then are probably wondering again, because the question that everyone keeps wanting to ask is, well, which one is the right one? And so let's talk about the three different approaches that I would say generally people have to choose between when it comes to this. And the first of which, as you can imagine, is just pure options API. So in other words, just to reiterate, what we have here is our component here with our explicit options, right, with data, computed methods, and we stick with the structure and we don't ever even deal with composition API.

Well, the thing about this is when it comes to the options in API, there are a couple of pros that I want to want to highlight, and the first of which is that it's very easy to learn, right? That's why I think one of the reasons Vue 2's API was so popular with people is because it was actually quite easy to understand as far as where things went, and everyone followed the same structure. And so even from my own personal experience, I taught someone who was basically a designer in tech but hadn't coded for years, but basically within the first hour of taking a Vue 101 workshop where they were concerned that they weren't going to be able to follow because their JavaScript skills really wasn't up to par. They were actually able to catch on really quickly, and before they knew it, they were actually following along and building things, which was really exciting for them, and they felt really empowered by that, and so this is one of the things I always remind people that options API is really great in this regard. And then, as we talked about, because it is extremely structured, you get a sense of consistency amongst the components because everyone knows data goes in data, computed goes in computed, and so forth. And as a result, you get a sense of simplicity, right? Especially when it comes to how the code is written and because you know every time that is predictable. But on the other hand, there are cons, right? Every decision in tech has trade-offs. That's something I always try to remind people when it comes to these sort of things, and so first of all, it is really opinionated.

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
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 Kuznetcov
Mikhail Kuznetcov
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
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.
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
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.
Building Pinia From Scratch
Vue.js Live 2024Vue.js Live 2024
70 min
Building Pinia From Scratch
Workshop
Eduardo San Martin Morote
Eduardo San Martin Morote
Let's dive into how Pinia works under the hood by building our own `defineStore()`. During this workshop we will cover some advanced Vue concepts like dependency Injection and effect scopes. It will give you a better understanding of Vue.js Composition API and Pinia. Requirements: experience building applications with Vue and its Composition API.