The computed function in Vue.js fails to provide a return value

I'm currently experimenting with a basic to-do list using vue.js. My goal is to calculate the total sum of all price values within an array. I created a small function under computed, but it seems like something isn't working correctly. Here's the snippet of my js code:

var app= new Vue({
  el: "#app",
  data: {
    message: "Shopping List",
    seen: true,
    todos: [
      {msg: 'parsley', price: 10},
      {msg: 'tomatoes', price: 20},
      {msg: 'zucchinis', price: 5}
    ],
  },
  methods: {
    addToDo: function() {
      if(this.name && this.price) {
        this.todos.push({msg: this.name, price: this.price});
      }
      this.name   = "";
      this.price = "";
    },
    RemoveThis: function(index) {
      this.todos.splice(index,1);
    }
  },
  computed: {
    totalSum: function() {
      var total = 0;

      this.todos.forEach(function(item) {
        total += item.price;
      });

      return total;
    }
  }
});

There seems to be an issue with the forEach loop causing the function to break. Any insights on what might be wrong?

Answer №1

When you pass the callback function to forEach, keep in mind that this doesn't refer to the component but is instead set to undefined by default.

https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

The callback function takes each todo as an argument, so an example implementation would appear like this:

total: function(){
  var sum = 0;
  this.todos.forEach(function (todo) {
    sum += todo.price
  });
  return total;
}

In practice, it's preferable to avoid using forEach and opt for reduce. When combined with an arrow function, it can be simplified into a neat one-liner:

total: function () {
  return this.todos.reduce((accumulatedSum, todo) => accumulatedSum + todo.price, 0)
}

Answer №3

Revise the code

this.items.forEach(function(){
    sum += this.items.cost
  });

with

this.items.forEach(function(data){
    sum += data.cost
  });

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

Is there a javascript file storing an image?

Currently, I am in the process of creating my personal portfolio website and incorporating react-bootstrap for designing my react components. I have been attempting to add an image using the Image component provided by react-bootstrap. However, I noticed ...

express: how to differentiate routing path based on request parameters

Currently, I am working on an API that is designed to receive a specific value from an Android client and then provide back a list of posts. One interesting aspect of this API is the request value known as req.body.sortType, which influences how the list o ...

How do I adjust the controls in Three.js to align with the previous camera position?

The three.js scene is equipped with W,A,S,D and left and right arrow controls, which allow for movement of the camera. However, the controls restrict the camera's movement to a fixed direction in the scene, rather than relative to its previous positio ...

Can you please tell me the title of my Vue component?

Currently experimenting with Vue for a small project. Initially, I was only using client code. As such, when I ran const mv = new Vue({...}); I could access the component externally using mv. Now that I'm utilizing Vue.cli, I define my component w ...

Adjusting image size according to browser dimensions

I've been struggling to resize a background image on my Square space website dynamically based on the user's browser window size. If the window width drops below a certain point, I want the image to adjust accordingly while maintaining its aspect ...

Tips for altering the appearance of a dropped item using JQueryUI sortable

I have a straightforward website where I need to implement the ability to drag and drop styled DIV elements between two containers. Utilizing JQueryUI's sortable function, this behavior was successfully achieved with the following code: $("#active-co ...

Sharing data between Vue.js v2 components and updating the parent when it's modified

My goal is to create a Form that can identify errors in its Inputs. Despite hours of effort, my current setup, which renders the inputs within a section of the form, is not functioning as intended. What would be the most effective approach to ensure this ...

Tips for transferring a JavaScript object to a Node.js server

I must admit, I am positive that the solution to my issue is incredibly simple yet it has been evading me for more than a week now and causing me endless frustration. My current project involves creating a web app for quoting purposes within my workplace, ...

How can a false validation be conducted on knockout js?

Using knockout js, I have an input type checkbox and I want to trigger the "not true" action when this checkbox is selected. Here's what I have attempted: <input type="checkbox" data-bind="checked: !IsVisible"/> Unfortunately, this code isn&ap ...

Creating a nested function and utilizing the return statement in JavaScript

I am facing an issue with my custom function that contains an ajax call. I need to retrieve a variable from the ajax function within my custom function, but I'm unable to do so. Why is this happening? Possible solution 1: <script> function ...

Is there a way to deactivate all dot inputs on number type input in vue.js 2?

Here is an example of my HTML code: <div id="app"> <input type="number" v-model="quantity"/> </div> This is how my Vue component looks: new Vue({ el: '#app', data: { quantity: '' }, watch: { quanti ...

Determining the position coordinates of an element in relation to the viewport using JavaScript, regardless of its relative positioning

I am currently developing a vueJs web application and I'm in need of determining the position of an element within my web app relative to the viewport itself, rather than its parent elements. I'm curious if there exists a function or property tha ...

In JavaScript, how is the symbol "." referred to as?

While I am familiar with its purpose and the language terminology, could you please provide the official name for the period/dot used in Javascript/jQuery? Appreciate your help! ...

Restricting the input on a React component to only accept alphabet characters from A to Z instead of allowing any keyboard

I am currently facing a challenge with understanding a specific component, particularly the allowForClassification value. This boolean value is passed down to a child component and decides whether a button is displayed or not. The issue arises when tryin ...

Having trouble with the date format in the highCharts range selector?

I am encountering an issue while trying to implement the rangefilter feature with HighCharts. The start and end dates are appearing incorrect, indicating that my date is not being recognized properly. My x-axis consists of unique dates as categorical valu ...

For every iteration, verify the presence of the image

I am currently working on a foreach loop to iterate over the data returned by an ajax call. Within this loop, I am checking if each record has an associated image. Code for Checking Image Existence: function checkImageExists(url, callback) { var img ...

Encountering syntax errors in GraphQL

Currently, I am in the process of working on the GraphQL Node tutorial and have reached step 7. Visit this link to view Step 7 While implementing the code in my datamodel.prisma file, I encountered several syntax errors: directive @id on FIELD_DEFINITIO ...

Waiting for data to be passed from a parent component within a method

I have a situation where I need to make an API call in my layout and send the received data as an object to my component. The problem arises because the object is empty when the method is called inside the mounted() function. Therefore, I want to execute ...

Experiencing issues calling a function in Vue.js while working with the SDK JavaScript?

When attempting to integrate the JavaScript SDK into Vuejs by utilizing a Facebook login button, I encountered an issue: <template> <div> <div class="fb-login-button" data-max-rows="1" data-size="large" data-button-type="login_with" d ...

How can I use D3.js to form a circular group in an organization structure, link it with a circular image, and connect

Is it possible to create a radial grouped circle using d3.js, similar to the image below: https://i.sstatic.net/1Hwd2.jpg I have written some code as shown below. However, I am facing challenges in connecting every circle with a curved line and displayi ...