Utilize Vue.js functions within data through the Vue.js context

I'm trying to incorporate a function as a data property. While it works for the 'works' data property, I need access to the this context within the function in order to calculate values from the shoppingCart property. Is there a way to achieve this? If so, how can I correct my approach?

 new Vue({
    el: '#vueApp',

    data: {

        shoppingCart: [],      

        works : function () {
            return "testfunc";
        },
        totalPriceCalcProperty : function () {

            this.totalPrice = this.shoppingCart.reduce(function(total, cartItem){

                console.log(total, cartItem);
                return total + parseFloat(cartItem.price);

            }, 0);
        }
    },

    methods: {

       totalPriceCalc: function () {

            this.totalPrice = this.shoppingCart.reduce(function(total, cartItem){

                console.log(total, cartItem);
                return total + parseFloat(cartItem.price);

            }, 0);
        },
    }

Answer №1

It is best practice to utilize methods instead of relying on data.
Using data primarily for storage purposes can lead to a more organized code structure.

With methods, you have the flexibility to access properties from data or property by simply calling this.xxx.

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

The mysterious case of jQuery DOM alterations vanishing from sight in the view

I have a quick inquiry. I've been exploring jQuery lately and discovered the ability to dynamically add HTML elements to the DOM using code like $('').append('<p>Test</p>'); However, what surprised me is that these ap ...

The code functions perfectly in the Adobe Dreamweaver Preview, but unfortunately, it is not compatible with Chrome

In the process of creating a website using Adobe Dreamweaver over the past few days, I encountered an issue with JavaScript that should activate upon scrolling. Interestingly, the script works perfectly fine when accessed through this link (), but fails t ...

Using JavaScript and jQuery to calculate the time difference between two values

Here is a code snippet for calculating the difference between two numbers: function calculateDifference(num1, num2) { if (num1 > num2) { return num1 - num2; } else { return num2 - num1; } } On document.ready event: var result = calculateD ...

Leveraging Firebase Dynamic Links through JavaScript

Currently exploring options for implementing Dynamic Links. Firebase Dynamic Links seem promising, but the lack of support for Cordova/ ionic apps is concerning. Is there any plan to add this in the future? Are there any other alternatives that you would ...

What is the process for encrypting and decrypting image files over the internet?

I'm currently developing a web application that requires loading images into a canvas object, followed by extensive manipulation. My goal is to conceal the original source image file (a jpeg) in such a way that users on the client side cannot access i ...

Press one button to activate another button

I am looking to activate a button's class by clicking on another button. The button I have is: <button class="clear-cart banner-btn">clear cart</button> This button is used for clearing a cart. On the order confirmation page, I click on ...

Ajax versus embedding data directly into the HTML code

Currently, my project involves a combination of JavaScript with jQuery and communication with a Django backend. Some aspects of the user interface require Ajax due to the fact that data to be sent is dependent on user input. On the other hand, there is c ...

Pass an array using AJAX to my Python function within a Django framework

I am attempting to pass an array to my python function within views.py, but I am encountering issues. It consistently crashes with a keyError because it does not recognize the data from js. Code: Python function in views.py: def cargar_datos_csv(request ...

The suggestions for auto-complete in jQuery are not showing up as expected

I am looking to implement a feature where suggestions from the database are automatically populated in a text box as I type. Additionally, when I select a suggestion, other related text fields should be filled automatically. Below is the code snippet: Vi ...

The issue of `function.prototype` not functioning correctly when used alongside `module

I have a file that contains a current function implementation function bar(){ /*Code goes here*/ } bar.prototype.method = function(param){ /*Some code*/ return this } module.exports = bar In the test file, I encountered some issues, let y = requir ...

javascript unable to change the text in the textarea

My application takes user input from a textarea element, calls an API to retrieve values, and then compares those values against a list of known "badwords." If a match is found, the word is highlighted in red to indicate it is spelled incorrectly. The pro ...

Bottom navigation in Vuetify fails to function properly on smaller screens

Utilizing Vuetify's bottom navigation component in my web application, I have implemented multiple sections that require navigation items on the bottom navigation bar. The code snippet below showcases the component being used: <template> < ...

The success callback in the first call will only be triggered when a breakpoint is established

I currently have an ASP.NET MVC webpage with Bootstrap and several plugins integrated. I am attempting to implement a confirmation message using the Bootbox plugin before deleting a record, followed by reloading the page upon successful deletion. Everythi ...

Developing a function that takes a parameter which can be used with or without an additional argument when invoked

In my React application, I have a method that accepts a parameter for displaying a modal. const displayModal = (p:Result) => { setConfirm(true); if(p) { //check variable for truthy setSelectedRow(p); } ...

Encountering the "ERPROTO" error message while attempting to send an Axios request from my REST API

I have set up my API at "localhost:3000/api/shopitems" and it successfully returns the JSON data below when accessed through a browser: [ { "item_available_sizes": { "s": 1 }, "imgs": { "album": [], ...

What is the best way to position my Jchartfx area graph below my gridview?

When my page loads, the graph appears like this. It consistently shows up in the top left corner even though it should be positioned underneath the grid view as intended. var chart1; function createGraph(mpy) { if (mpy == undefined) mpy = 12.00; ch ...

Is there a possibility of Typescript expressions `A` existing where the concept of truthiness is not the same as when applying `!!A`?

When working with JavaScript, it is important to note that almost all expressions have a "truthiness" value. This means that if you use an expression in a statement that expects a boolean, it will be evaluated as a boolean equivalent. For example: let a = ...

Using jQuery to animate a form submission in CodeIgniter

I have integrated two jQuery plugins into my application, which are: jQuery validate : . jQuery blockui : http://malsup.com/jquery/block/#download The application is developed using PHP Codeigniter and jQuery. It consists of a form created with the fol ...

ESLint: The "react" plugin encountered a conflict

In my development environment, I have a React application within a single npm component package. This React app acts as a demonstration site that consumes the component package in addition to Storybook. local-component-package ├── .storybook ├─ ...

How to efficiently pass props between components in NextJs

This is the project's file structure: components ├─homepage │ ├─index.jsx ├─location │ ├─index.jsx pages │ ├─location │ │ ├─[id].jsx │ ├─presentation │ │ ├─[id].jsx │ ├─_app.jsx │ ├─index.jsx ...