A comparison between the Composition API and traditional Plain JavaScript syntax

I'm currently exploring the necessity of utilizing the 'new' Vue Composition API.

For instance, take the following component extracted from their basic example:

<template>
  <button @click="increment">
    Count is: {{ state.count }}, double is: {{ state.double }}
  </button>
</template>

<script>
import { reactive, computed } from '@vue/composition-api'

export default {
  setup () {
    const state = reactive({
      count: 0,
      double: computed(() => state.count * 2),
    })

    function increment () {
      state.count++
    }

    return {
      state,
      increment,
    }
  },
}
</script>

We could alternatively present this in a 'composition style' using vanilla JavaScript and expose it through the data option:

<template>
  <button @click="increment">
    Count is: {{ state.count }}, double is: {{ state.double }}
  </button>
</template>

<script>
export default {
  data () {
    const state = {
      count: 0,
      get double () {
        return this.count * 2
      },
    }

    function increment () {
      state.count++
    }

    return {
      state,
      increment,
    }
  },
}
</script>

Are there notable distinctions between these options? What particular benefits does the Composition API offer?

Answer №1

Quoted from @linusborg in the Vue Discord server:

The primary objective of the composition API is to simplify and enhance code composition, replacing the usage of mixins. By separating logic from this and the Options object, it enables us to extract functionality into simple Javascript functions that can be composed in setup.

This style of composition offers numerous advantages over Vue 2 mixins, such as ease of typing in TypeScript, better visibility of dependencies in code, among others. The main focus is on improving composition patterns and addressing issues associated with mixins.

While the code example demonstrates good composability to some extent:

function reusableState () {
  const state = {
    count: 0,
    get double () {
      return this.count * 2
    },
  }

  function increment () {
    state.count++
  }

  return {
    state,
    increment,
  }
}

export default {
  data () {
    return reusableState()
  },
}

It fails to incorporate other essential features like:

  • watch
  • computed properties (getter used here is not cached)
  • lifecycle hooks (mounted, updated)

If you have logic that needs to be reusable or composable but relies on these features, extracting it into a function like this may not be feasible.

This is where the composition API functionalities such as computed(), ref(), onMounted() come into play.

For a detailed analysis of the design and advantages of the composition API, visit:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a stylish Go URL bar using HTML and CSS

Looking for some guidance in JavaScript as I am new to it. I want to create a go bar similar to the ones found at the top of browsers using HTML and JS. When the button is clicked, it should navigate to the URL entered in the box. Here's an example of ...

Error: Unable to access the 'resource' property as it is undefined

I am currently working on a project that involves fetching the latest 4 results from Craigslist using a query. Although I have successfully retrieved all the relevant information, I seem to be encountering an issue with loading the URL of the image from th ...

Tips for overlaying text on the background in Next.js:

I'm currently working on creating an image element with overlay text. Check out my jsx code below: <div className={styles.img}> <img src={src} alt="" /> <p>{`(${size})`}</p> </div> And here is t ...

Unable to retrieve observable modifications

In my code file for handling reports, named report.service.ts, I have a method that retrieves reports data. This method simply returns a constant array of report objects from a mock source. Here is the implementation: @Injectable() export class ReportServ ...

Ways to showcase HTML table in a four-column layout/grid

Delving into Dynamic HTML table creation, I'm currently using jquery for rendering purposes. At the moment, I am only displaying the table. The Goal I aim to segment my table into four columns or a grid structure Something akin to this: https://i. ...

Utilizing React Views in an Express Environment

I am struggling to find a simple example that demonstrates how to connect an Express.js route to render a React view. This is what I have tried so far. +-- app.js +-- config | +-- server.js +-- routes | +-- index.js +-- views | +-- index.html app. ...

You can activate Lightgallery just one time in VueJs

I am facing an issue where lightgallery can only be opened once. Subsequent clicks on the button are unresponsive. The lightgallery is being used as a component. Within my parent component, I have two buttons for opening image or video gallery ParentComp ...

Is it illegal to escape quotes when using an image source attribute and onerror event in HTML: `<img src="x" onerror="alert("hello")" />`?

Experimenting with escape characters has been a fascinating experience for me. <img src="x" onerror=alert('hello'); /> <img src="x" onerror="alert(\"hello\")" /> The second code snippet triggers an illegal character error ...

Rzslider not functioning properly due to CSS issues

I am facing an issue where rzslider is not appearing in my app. However, when I copy the code to an online editor, it works perfectly fine. Below is the code snippet: var app = angular.module('rzSliderDemo', ['rzModule', 'ui.boo ...

Vue 3 list fails to refresh

Using an API, we are retrieving data: <script setup> import { onMounted, inject } from 'vue' let list = []; function initializeData() { axios .post("/some-link/here") .then((response) => { list ...

Unlock the full potential of custom authorization providers when integrating them with Supabse

Supabase user here looking to implement authorization with a third-party service that isn't on the supported list. Any suggestions on how to go about this? ...

The function of the React index key appears to be malfunctioning within the map function

I've been encountering issues despite using the index key and also attempted utilizing a unique id from JSON data, but unfortunately haven't found a solution yet. ERROR Warning: Each child in a list should have a unique "key" prop. const fa ...

What are some ways to prevent having to constantly check for the existence of an object within another object when working

<template> <img :src="user.avatar_thumbnail"> <a :href="user.profile.link"/> </template> <script> export default { data: function () { user: {} }, ...

The sequence of error middleware in Express4

Encountered a series of code execution that seemed unusual. Here's the code snippet: server.js const Actions_Single_PVC = require('./routes/Actions_single_PVC.js'); app.use('/Actions_single_PVC', Actions_Single_PVC); app.use((e ...

Utilizing JSON instead of GeoJSON with AJAX in Leaflet

I am in search of a method to utilize JSON instead of GeoJSON with leaflet, making use of AJAX. The use of JSON and AJAX is imperative for this task. I have successfully called a JSON file using AJAX. However, I am now unsure about how to effectively util ...

The choice between invoking a function within a route handler or employing a middleware for the task

I am currently exploring a potential difference in coding approaches. Let me illustrate this with an example excerpted from the express documentation: https://expressjs.com/en/guide/using-middleware.html function logOriginalUrl (req, res, next) { console ...

Clicking on AngularJS ng-click to navigate to a different page within an Ionic framework application

My goal is to navigate to another page when clicking on a button in the Ionic navbar at the top. However, I am encountering an issue where upon clicking, all nav bar buttons disappear. Interestingly, using dummy codes triggers an alert successfully. But w ...

Fetching Data Using Asynchronous API Calls

My goal is to retrieve all results consistently from the API, but I am encountering varying outcomes. The for loop seems to be skipping some requests and returning a random number of records. Can anyone provide assistance? I have experimented with using t ...

The issue with triggering button events in JavaScript

I've integrated a jquery modal popup for saving uploaded files related to a specific device. The modal appears, the cancel button functions correctly, but I am struggling to trigger the onclick event for the Save button... This is what I have impleme ...

Using Jquery $.ajax may lead to temporary freezing of the Browser

I have a $ajax function that fetches multiple JSON objects from a URL and converts them into divs. There are around 50 objects, and I am using setInterval to call the $ajax function every 10 seconds for updates on each of the created divs. However, I' ...