Switching from using a computed property in Vue 2 to implementing the Vue 3 Composition API

I am currently in the process of updating my Vue 2 application to Vue 3 and I have been exploring how to work with computed properties using the Composition API in Vue 3.

One particular challenge I am facing is migrating a Vue 2 computed property that provides common data to multiple components. I am wondering how I can achieve the same functionality in Vue 3 using the Composition API, specifically with getters and setters.

sharingDataInComponents() {
        let obj={}, objProperty = Object.defineProperty;
        // variables
        objProperty(obj, 'size'   , {get:()=>this.size});
        objProperty(obj, 'shape'  , {get:()=>this.shape});
        objProperty(obj, 'navigation'   , {get:()=>this.navigation});
        objProperty(obj, 'addBtn' , {get:()=>this.addBtn});
         // functions
        objProperty(obj, 'onAddClick', {get:()=>this.onAddClick});

        return obj;
    },

As I am new to the Vue 3 Composition API, I would appreciate guidance on how to successfully migrate this computed property. Thank you!

Answer №1

Check out the code snippet below for an example:

const { ref, computed } = Vue
const app = Vue.createApp({
  setup() {
    const size = ref(35)
    const shape = ref('circle')
    const navigation = ref('left')
    const addBtn = ref(true)
    const onAddClick = () => {console.log('add')}
    
    const sharingDataInComponents = computed(() => {
      let obj={}, objProperty = Object.defineProperty;
        // variables
        objProperty(obj, 'size'   , {get:()=>size.value});
        objProperty(obj, 'shape'  , {get:()=>shape.value});
        objProperty(obj, 'navigation'   , {get:()=>navigation.value});
        objProperty(obj, 'addBtn' , {get:()=>addBtn.value});
         // function
        objProperty(obj, 'onAddClick', {get:()=>onAddClick});

        return obj;
    })
    
    return { size, shape, navigation, addBtn, onAddClick, sharingDataInComponents }
  }
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
  <div @click="sharingDataInComponents.onAddClick">
    {{ sharingDataInComponents.size }}
  </div>
</div>

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

Button press triggers the fadeIn function successfully, but the keypress event does not have the same effect

I'm currently facing an issue with two div elements on my webpage. I want only one of them to be visible at a time, depending on which key is pressed. If the 1 key is pressed, I want 'div1' to fadeIn (if it's not already visible) and fo ...

Unable to utilize ES6 syntax for injecting a service

I am encountering some issues while trying to implement a service into a controller using ES6 syntax. CategoriesService.js export default class CategoriesService { constructor() { this.getCategories = function ($q) { var deferred ...

Uh oh! An error occurred when trying to submit the form, indicating that "quotesCollection is not defined" in Mongodb Atlas

Displayed below is my server.js file code, along with the error message displayed in the browser post clicking the Submit button. const express = require('express'); const bodyParser = require('body-parser'); const MongoClient = require ...

Chrome is experiencing a problem with anchor tags that have an href attribute set to a "blob:" URL and using a target of "_blank"

My current project involves developing a website feature that allows users to download a PDF version of a page. To achieve this, the generated HTML is rendered into a PDF on the server, which is then returned as a Base64-encoded PDF. This data is converted ...

Set up your Typescript project to transpile code from ES6 to ES5 by utilizing Bable

Embarking on a new project, I am eager to implement the Async and Await capabilities recently introduced for TypeScript. Unfortunately, these features are currently only compatible with ES6. Is there a way to configure Visual Studio (2015 Update 1) to co ...

Transform an array of objects into a nested tree structure with Javascript

I am currently facing a challenge with handling a complex json file using javascript to structure it hierarchically. My goal is to convert an array of objects into a deeply nested array, where there can be multiple divNames with varying categories and subc ...

How can I filter rows in HTML using Vue.js based on string options?

When selecting different options, I want to dynamically add new rows. For instance, if "kfc" is selected, a specific row should be added. If "cemrt" is chosen, another row needs to be included. <div class="card-content" v-for="(bok, index) in rules" :k ...

The section cannot be shown in a flex layout within a grid container

My goal is to showcase a grid layout containing multiple sections within a div, but I'm encountering an issue where the sections are only displaying as blocks. I am seeking assistance in making the second portion of the data appear flexed. Currently, ...

Switch it up - modify the directory for static assets

I developed an application using create-react-app. Our server configuration stores all files, except for index.html, in a folder named static. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> ...

Querying data with parameters in a client-side rendered application with Next.js

Currently, I am developing a chat application using Next.js and Axios. One of the functionalities I implemented is a dynamic route called chat/:pid to fetch data using the provided pid. However, I encountered an issue where the values are coming back as un ...

The hyperlink tag within the overlay div is unresponsive

I'm facing an issue with my overlay div (rb-overlay) that pops up when users click on a page option. The overlay takes up the entire page and includes a close button in the top right corner. However, I've noticed that the link at the end of the t ...

Implementing component method calls in store.js

In my Login.vue component, I have a method called postData() postData() { this.$store.dispatch('doLogin', fdata) }, The doLogin method is located in store.js actions: { doLogin({ commit }, loginData) { commit('loginStart ...

The challenge of populating information within a Datalist

In my code snippet, I have a JavaScript function that is used to populate a Datalist: function PopulateDropDown(facility) { $.ajax({ url: '/Rentals/Base/GetContactsForFacility?selectedFacility=' + facility, data: { facility: ...

Different ways to enhance max-http-header-size in Vue application

After being redirected from another application, I am unable to open the page and receive an error in the console: Failed to load resource: the server responded with a status of 431 (Request Header Fields Too Large). I came across information about max-h ...

Encountering an issue: Unable to load resources - Server returned a status code of 500

Struggling with implementing ajax code in my app development. I've encountered an issue where the ajax code that works fine in the video tutorials I'm following doesn't seem to work for me. It's really frustrating! Here is a snippet of ...

The best way to handle custom errors between Backend (Express) and Frontend (Vue)

While working on a simple Node application, I have encountered an issue that seems familiar but I am unsure of the correct approach to resolve it. The challenge lies in handling errors that are not directly related to code, network connectivity, or databas ...

Undo a CSS transition when clicked

There is a div named learn-more which expands to fill the whole page when a CSS class is added like this: .learn-more{ padding:10px; font-size: 20px; text-align: center; margin-top:20px; font-family: klight; -webkit-transition:2s; ...

Even after setting the handler to return false, Angular continues to submit the form

In the following scenario, I have encountered an issue: Here is the HTML template snippet: <form [action]='endpoint' method="post" target="my_iframe" #confirmForm (ngSubmit)="submitConfirmation()"> <button type="submit" (click)="conf ...

Can one intercept the window.location.replace event?

Suppose I am currently browsing the URL "example.com/somepage#somehash" and then decide to execute window.location.hash = "anotherhash", the URL will be updated to "example.com/somepage#anotherhash". This action triggers the window.hashashchange event. On ...

Change from one value to another using a decaying sinusoidal wave

Can someone help me come up with a formula that will smoothly transition from a starting value to an end value over a specified time using a Sin or Cos wave? I'm attempting to replicate a bouncing effect like the one shown in my sample using CSS and ...