What is the best way to create a new object in a Vue component with optimal efficiency?

Currently, I am working on initializing a map that would be utilized in my calculatePrice function.


calculatePrice(key) {

    let prices = new Map({
        0: 17,
        1: 19,
        2: 24,
        3: 27,
        4: 30,
        5: 46,
        6: 50,
        7: 54,
        8: 58,
        9: 67,
        10: 75,
    });

    let price = prices.get(key);
    return price;
},

However, considering the frequent invocation of this method (using @change within a form field), it might not be efficient for performance to create this object every time the method is called. Is there a better location within a view component to store "prices" where it can be initialized when the page loads and accessed whenever the method is invoked without requiring recreation?

Answer №1

This appears to be a universal constant specific to your component. Consider defining it outside of the component, while keeping it within the same scope (or importing it from elsewhere).

Answer №2

Include it as part of the data object:

export default {
    name: 'ComponentName',
    data() {
        return {
            prices: {
                0: 17,
                1: 19,
                2: 24,
                3: 27,
                4: 30,
                5: 46,
                6: 50,
                7: 54,
                8: 58,
                9: 67,
                10: 75,
            }
        }
    },
    methods: {
        getPrice(key) {
            return this.prices[key];
        }
    }
}

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

Increase and decrease buttons using the 'keydown' event (ArrowUp and ArrowDown)

I'm seeking assistance with a school project. I currently have two buttons, one for incrementing and one for decrementing. There are four functions in total, two for clicking and two for using arrow keys. The clicking functionality works fine, but whe ...

I am looking to retrieve a specific input value from a JSON array using JavaScript

I have created an array called 'PROPERTIES' which accepts values like username, password, sid, etc. I am looking to retrieve these entered values using JavaScript. 'PROPERTIES': {'gatewayurl': {'Name': ...

Generate HTML content using AngularJS

Is there a way to format a string as HTML when using it in the following syntax: <div> {{ text }} </div> Instead of displaying the actual HTML, only the text is shown - for example " ab " ...

What steps should I take to make sure the vuex store is included in my build process?

I am currently working on a Vue application using vue cli 3. I found a guide here that explains how to build the app with vue-cli-service build --target wc --name my-element [entry] In order to test the output, I have created an index.html file: <!D ...

A step-by-step guide on recovering information from a JSON file within Angular 12

Being a novice developer, I have taken on the challenge of creating a quiz application using Angular 12 to enhance my coding skills. However, I've hit a roadblock when it comes to retrieving data with questions and answers from a JSON file. Despite su ...

Having trouble simulating a service using nuxt and jest

In my project, I have created a component named External.vue. This component includes a button with props and triggers a Google Analytics event whenever it is clicked. <template> <div> <button ref="ctaButtonExternalElement&q ...

The input type "number" does not seem to be compatible with the currency pipe feature

The currency pipe seems to not be working when using the input type number. The web page is not displaying any value. I have searched various blogs and it appears that the currency pipe only works with input type text, but my requirement necessitates the ...

What other options are available for achieving the same functionality as FormData.delete() given its low level of support?

When building my website, I utilized the FormData.delete() method to exclude specific form fields before sending data to the server. However, I encountered a setback as this method is not supported on various browsers, including Safari. Therefore, I am in ...

Tips for dynamically inserting JSON data into HTML elements

{ "top10": [ { "state": "red", "claimed": true, "branch": "release-2.3.4", ...

A guide on integrating a stacked bar chart from ApexCharts into a modal or v-dialog component

I'm facing a minor issue with vue-apexcharts while attempting to showcase some data in a stacked bar chart. Here is the simple component I have created: <template> <div v-if="this.loaded"> <apexchart w ...

How can I prevent buttons from being created using ngFor in Angular?

I need help with creating an HTML table that includes a cell with a button and a dropdown generated using ngFor. How can I disable the buttons (generated via ngFor) if no value is selected from the dropdown? Here's what I have tried so far: In my App ...

Content that moves with a flick of a finger

Seeking advice on a widely used JavaScript library that can facilitate scrolling for frequently updated content, similar to what popular websites like have implemented. I've had difficulty finding the right query on Google, so any recommendations or ...

Encountering an issue with Material-UI and Next.js: "TypeError: theme.spacing is not a function

Encountering an issue after modifying _app.js to dynamically generate a material UI theme. I've been following the implementation example provided by the material-ui team at: https://github.com/mui-org/material-ui/tree/master/examples/nextjs. To summ ...

My bootstrap collapse navbar isn't functioning properly. Despite pressing the icon on a smaller screen, the menu fails to open. Can anyone provide a solution to this issue?

The hamburger menu is not working properly. I am facing an issue where the navigation does not appear when I press on the hamburger icon on a small screen. Can someone please guide me on how to resolve this problem? :/ <nav class="navbar bg-d ...

Is it problematic to assign computed values to a ref property within Vue?

Recently, I came across some Vue code that caught my attention. The developer had assigned a computed value to a ref property, which was quite unusual in my experience. The code functions as expected, but it still gives me a sense of unease. Should I be c ...

Problem with repetitive looping of Jquery click event within an Angular controller

Currently, I am in the process of creating an app using onsen UI (angular based) + phonegap. One issue I am facing is related to a JQuery click event inside an angular controller. The problem arises when I navigate back through the page stack and then ret ...

Having trouble with deploying Node.js to Heroku? Feel like your 'git push her

After successfully running my app locally, I encountered an issue when trying to deploy it to Heroku. The deployment process just hangs indefinitely and only displays one public file on the website with an error message stating: "https://analogy-alley.hero ...

Is it possible to display a pdf.js page as actual HTML elements rather than as canvas or SVG?

I am in the process of creating a user-friendly mobile interface for pdf reading. However, I want to incorporate more advanced features by developing my own pdf reader instead of relying on the pdf.js team's viewer. Is there a method available to rend ...

Guide on organizing users into groups and filtering them using Firestore's reference field type

I currently manage a small group of employees with plans to expand in the future. To streamline operations, I am looking to implement a grouping feature that allows users to sort employees based on their assigned groups. Although I thought about using the ...

Enhance global variable by appending a line from a local function in Javascript

In my js files, I have some global functions that are used in all modules of the application. Currently, I am working on a module that requires modifying one of these global functions to run a local script every time it is called. The issue is that the g ...