DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Exploring Intercooler.js: Simplify AJAX With HTML Attributes
  • Migrating from React Router v5 to v6: A Comprehensive Guide
  • React’s Unstoppable Rise: Why It’s Here to Stay
  • How to Create a Pokémon Breeding Gaming Calculator Using HTML, CSS, and JavaScript

Trending

  • Building Reliable LLM-Powered Microservices With Kubernetes on AWS
  • Software Delivery at Scale: Centralized Jenkins Pipeline for Optimal Efficiency
  • Traditional Testing and RAGAS: A Hybrid Strategy for Evaluating AI Chatbots
  • Manual Sharding in PostgreSQL: A Step-by-Step Implementation Guide
  1. DZone
  2. Coding
  3. JavaScript
  4. Vue 3 Composition API

Vue 3 Composition API

The change from Vue 2 to Vue 3 offers several options to developers when assembling the logic of a component.

By 
Xavi Llordella user avatar
Xavi Llordella
·
Oct. 07, 23 · Analysis
Likes (1)
Comment
Save
Tweet
Share
5.7K Views

Join the DZone community and get the full member experience.

Join For Free

In this article, we assume that you know the basics of Vue 3. In the cited article, the main changes from Vue 2 to Vue 3 are explained, as is the basis for understanding how the composition API functions. The latter would be the main topic of this article: the Vue 3 Composition API.

Vue 3 Composition APIs

The change from Vue 2 to Vue 3 offers several options to developers when assembling the logic of a component. We can continue using the Options API as we were doing in Vue 2 or use the Composition API.

Advantages of Composition API

The main advantage is the ability to extract the logic and reuse it in different components, making our code more modular and easier to maintain. So we avoid having to use mixins, which was the way to reuse logic in Vue2.  

If we continue talking about the organization, in the Options API, if we explore our component, we will realize that each component is in charge of many responsibilities that will be forced to be divided into different parts of the code. That forces us to scroll up and down if the file has hundreds of lines, making it more complicated than it should be. Therefore, if we try to extract the logic in reusable parts, although it may involve a little more work, we will see that the result is much cleaner and tidier, we can see it in the following image:

Some used API's


Another important advantage is that it allows functional programming, unlike the Options API which is object oriented.

Code written using the Composition API is more efficient and modifiable than Options API code, so the bundle size will be smaller. This is because the template in our <script setup> is compiled   inline function within the same code scope. Unlike the this property, the compiled code can directly access the variables without a proxy. Because of this, it helps us to have less weight by being able to have simplified variable names.

The new API allows you to take full advantage of Javascript by defining the behavior of our component, async/await, promises, and facilitates the use of third-party libraries such as RxJS, among others.

Disadvantages of Composition API

The main disadvantage is that it forces developers to learn a new syntax and way of organizing code. This can have a learning curve for those who are used to Options API. Still, it is designed to be simple and easy to learn, so the curve should be fast.

First Steps

Template:

HTML
 
<template>
  <button @click="increment">Count is: {{ count }}</button>
</template>


Options API:

JavaScript
 
<script>
export default {
  // Properties returned from data() become reactive state
  // and will be exposed on `this`.
  data() {
    return {
      count: 0
    }
  },

  // Methods are functions that mutate state and trigger updates.
  // They can be bound as event listeners in templates.
  methods: {
    increment() {
      this.count++
    }
  },

  // Lifecycle hooks are called at different stages
  // of a component's lifecycle.
  // This function will be called when the component is mounted.
  mounted() {
    console.log(`The initial count is ${this.count}.`)
  }
}
</script>


Composition API:

JavaScript
 
<script setup>
import { ref, onMounted } from 'vue'

const count = ref(0)

const increment = () => {
  count.value++
}

onMounted(() => {
  console.log(`The initial count is ${count.value}.`)
})
</script>


Comparison With React Hooks

Compared with React Hooks, the logic is the same, but with some differences.

React Hooks:

  • Hooks are invoked whenever there is an update of the component.
  • Variables declared in a hook closure may become obsolete if the correct dependencies are not passed.
  • Heavy computations must be used useMemo which will require us to pass dependencies manually.
  • The Event handlers passed to secondary components cause unnecessary code updates by default. Neglecting this causes an excessive update affecting performance almost without realizing it.

Vue Composition API:

  • The setup()or <script setup> code is invoked only once.
  • Vue’s reactivity system  runtime retrieves the reactive dependencies, so we don’t need to declare them manually.
  • There is no need to manually control the callback functions to update the child components. Vue ensures that components are only updated when they are really needed.

That said, react hooks were a major source of inspiration for creating the Composition API, but trying to solve the problems mentioned above.

FAQs

Will Options API Be Deprecated?

No, it’s not planned, it’s part of Vue and there are many developers who love it. Besides, many of the benefits of the Composition API can only be felt in large projects, so Options API is still a good choice for small and medium projects.

Can I Use Both APIs Together?

Yes, you can use Composition API using the setup() method in the Options API. However, it is recommended only if you have your code in Options API and you need to integrate some library written in Composition API.

Is the Composition API Compatible With Vue 2?

No, you must upgrade your project Vue 3 in order to use the Composition API.

Conclusion

In conclusion, both APIs are valid for the logic of a Vue component. The Composition API offers us a functional and reusable way to organize our code, while the Options API offers us the traditional solution: Object oriented. Still, if what you want is better performance, and better code readability and you are in a large project, your choice should be Composition API.

API Functional programming IT JavaScript Vue.js Functional reactive programming Microsoft Developer Network

Published at DZone with permission of Xavi Llordella. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Exploring Intercooler.js: Simplify AJAX With HTML Attributes
  • Migrating from React Router v5 to v6: A Comprehensive Guide
  • React’s Unstoppable Rise: Why It’s Here to Stay
  • How to Create a Pokémon Breeding Gaming Calculator Using HTML, CSS, and JavaScript

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!