Calculating the function using data in a Vue component

Here is a Vue component along with some data:

    Vue.component('receipt', {
    template: '#receipt-template',
    data: function() {
        return {
            tip: 8.50
        };
    },
    computed: {
        subtotal: function() {
            return this.sales.price;
            console.log(this.sales.price);
        }
    },
    props: ['header', 'date', 'sales' ]
})

new Vue({
    el: '#content',
    data: {
        sales1: [
            {amount: 1, desc: 'A book title', price: 13.99},
            {amount: 3, desc: 'An espresso title', price: 5.00},
            {amount: 6, desc: 'A drink title', price: 4.25},
            {amount: 2, desc: 'A pastrt', price: 3.99}
        ],
        sales2: [
            {amount: 1, desc: 'A title', price: 9},
            {amount: 2, desc: 'An title', price: 0},
            {amount: 3, desc: 'A title', price: 5},
            {amount: 4, desc: 'A ', price: 99}
        ]
    }
})

And there's also a corresponding template:

<div class="page page2 current">

        <!-- Using the custom receipt vue component -->
        <receipt header="Between the Covers &amp; Grinders Café" date="Sept. 23, 2016 10:52 am" :sales="sales1"></receipt>
        <receipt header="Between the Covers &amp; Grinders Café" date="Sept. 25, 2016 3:08 pm" :sales="sales2"></receipt>

        <div class="clearfix"></div>

    </div><!--end page2-->

    <template id="receipt-template">
        <div class="receipt">
                <div class="receipt-header">
                    <h2>{{ header }}</h2>
                </div><!--end receipt-header-->
                <div class="receipt-body">
                    <div class="receipt-labels">
                        <p>Sales</p>
                        <p>{{ date }}</p>
                        <div class="clearfix"></div>
                    </div><!--end receipt-labels-->
                    <div class="receipt-sales">
                        <div class="receipt-sale-row" v-for="sale in sales">
                            <p>{{ sale.amount }}</p>
                            <p>{{ sale.desc }}</p>
                            <p class="sale-price">${{ sale.price }}</p>
                        </div><!--end receipt-sale-row-->
                    </div><!--end receipt-sales-->
                    <div class="receipt-subtotals">
                        <p>Subtotal</p>
                        <p>{{ subtotal }}</p>
                        <p>Tax</p>
                        <p>$2.64</p>
                        <div class="clearfix"></div>
                    </div><!--end subtotals-->
                    <div class="receipt-totals">
                        <p>Tip</p>
                        <p>{{ tip }}</p>
                        <p>Total</p>
                        <p></p>
                        <div class="clearfix"></div>
                    </div><!--end totals-->
                    <div class="receipt-card">
                        <p>Visa 1825</p>
                        <p>$41.25</p>
                        <div class="clearfix"></div>
                    </div><!--end card-->
                </div><!--end receipt-body-->
            </div><!--end receipt-->
    </template>

I'm struggling with computing the 'subtotal'. I want the computed function 'subtotal' to return the total of all prices for each 'sales' object. What am I missing?

Answer №1

To calculate the total price of all items in this.sales, you need to sum up each individual price.

subtotal: function() {
  let result = 0;

  this.sales.forEach((sale) => result += sale.price);
  return Math.round(100 * result) / 100;
}

Vue.component('receipt', {
  template: '#receipt-template',
  data: function() {
    return {
      tip: 8.50
    };
  },
  computed: {
    subtotal: function() {
      let result = 0;
      
      this.sales.forEach((sale) => result += sale.price);
      return Math.round(100 * result) / 100;
    }
  },
  props: ['header', 'date', 'sales']
});

new Vue({
  el: '.page.current',
  data: {
    sales1: [{
      amount: 1,
      desc: 'A book title',
      price: 13.99
    }, {
      amount: 3,
      desc: 'An espresso title',
      price: 5.00
    }, {
      amount: 6,
      desc: 'A drink title',
      price: 4.25
    }, {
      amount: 2,
      desc: 'A pastry',
      price: 3.99
    }],
    sales2: [{
      amount: 1,
      desc: 'A title',
      price: 9
    }, {
      amount: 2,
      desc: 'An title',
      price: 0
    }, {
      amount: 3,
      desc: 'A title',
      price: 5
    }, {
      amount: 4,
      desc: 'A ',
      price: 99
    }]
  }
});
.receipt-subtotals p,
.receipt-labels p,
.receipt-sale-row p,
.receipt-totals p {
  display: inline-block;
  margin: 1rem;
}
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/1.0.26/vue.min.js"></script>
<div class="page page2 current">

  <!-- Call our custom receipt vue component -->
  <receipt header="Between the Covers &amp; Grinders Café" date="Sept. 23, 2016 10:52 am" :sales="sales1"></receipt>
  <receipt header="Between the Covers &amp; Grinders Café" date="Sept. 25, 2016 3:08 pm" :sales="sales2"></receipt>

  <div class="clearfix"></div>

</div>
<!--end page2-->

<template id="receipt-template">
  <div class="receipt">
    <div class="receipt-header">
      <h2>{{ header }}</h2>
    </div>
    <!--end receipt-header-->
    <div class="receipt-body">
      <div class="receipt-labels">
        <p>Sales</p>
        <p>{{ date }}</p>
        <div class="clearfix"></div>
      </div>
      <!--end receipt-labels-->
      <div class="receipt-sales">
        <div class="receipt-sale-row" v-for="sale in sales">
          <p>{{ sale.amount }}</p>
          <p>{{ sale.desc }}</p>
          <p class="sale-price">${{ sale.price }}</p>
        </div>
        <!--end receipt-sale-row-->
      </div>
      <!--end receipt-sales-->
      <div class="receipt-subtotals">
        <p>Subtotal</p>
        <p>${{ subtotal }}</p>
        <p>Tax</p>
        <p>$2.64</p>
        <div class="clearfix"></div>
      </div>
      <!--end subtotals-->
      <div class="receipt-totals">
        <p>Tip</p>
        <p>{{ tip }}</p>
        <p>Total</p>
        <p></p>
        <div class="clearfix"></div>
      </div>
      <!--end totals-->
      <div class="receipt-card">
        <p>Visa 1825</p>
        <p>$41.25</p>
        <div class="clearfix"></div>
      </div>
      <!--end card-->
    </div>
    <!--end receipt-body-->
  </div>
  <!--end receipt-->
</template>

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

Verify the presence of values in several textarea fields with jQuery before executing a specified action

My main goal is to validate multiple dynamic forms on a single page. If all textareas are either empty or contain default values, I need a specific function to be executed. However, if any of the textareas have content that deviates from the default value, ...

Create a feature that allows users to view photos similar to the way it

I want to incorporate a Twitter feed on my website that displays images posted. Instead of having the images redirecting users to Twitter when clicked, I would like them to reveal themselves underneath when a link labeled "View Photo" is clicked, and then ...

Unable to retrieve or remove cookie sent from Express on client side

My Express server is sending a cookie to the client that is not httpOnly. Despite this, the client is unable to access the cookie through document.cookie or see it in the Application tab on chrome dev tools. Interestingly, I am able to view the cookie in C ...

The scrollOverflow feature in fullPage.js is not properly detecting the height of dynamically generated content

I have successfully implemented fullpage.js on my website. Everything is working perfectly with fullpage.js, but I am facing an issue when trying to open a div on click of pagination. Specifically, the browser scroll gets disabled when the div containing a ...

Tips for updating and using a map value array as state in React

One React state I am working with is as follows: const [tasksMap, setTasksMap] = useState(new Map()); This map is created using the following code: tasks.forEach((task) => { const key = `${week.year}-${week.weekNo}`; if (!tasksMap.has(key)) { ...

Utilizing variables in GraphQL requests

UPDATE: see the working code below GraphiQL Query I have this query for retrieving a gatsby-image: query getImages($fileName: String) { landscape: file(relativePath: {eq: $fileName}) { childImageSharp { fluid(maxWidth: 1000) { base64 ...

Organize an array based on its ratio

I am attempting to organize an array based on the win and lose ratio of each player. This is how my code currently looks: const array = [{playerName: 'toto', win: 2, lose: 2}, {playerName: 'titi', win: 0, lose: 0}, {playerName: &apo ...

Determine whether two inputs are identical by comparing them

Currently, I am in the process of creating a form for users to update their passwords. The form includes a field for entering a new password and another field for confirming the new password to ensure it has been entered correctly. However, I am facing so ...

Transform the string response in a websocket message into JSON format

When receiving a websocket message, I often encounter a response in the form of a string like this: odds.1:[{"id":1,"marketType":10,"name":"Double chance","status":"HandedOver","specifiers":"","Outcomes":[]},{"id":2,"marketType":11,"name":"Draw no bet", ...

How can we access the property object from an API using Vue.js and Vuetify's v-select component?

I've been having trouble with v-select. I have received an array of objects from a backend API and I want to display those objects in my v-select element. Here is my code: <v-select label="Expedition" :items="expeditions ...

Encountering a 404 error in Codeigniter when making an AJAX call

After successfully implementing an upload form with ajax, I encountered some issues when attempting to delete uploaded photos. Initially, I received a "csrf protection error," which led me to disable csrf protection, only to then encounter a "404 not found ...

A technique for simultaneously replacing two values in a single call to the replace function

Is there a way to replace two or more instances at once with a single replace call? I have not attempted anything yet, as I am unsure of how to proceed. let links = { _init: "https://%s.website.com/get/%s", } Here, you can see that I have a link wi ...

What is the best way to assign JSON data to a Class variable within Angular?

In my code, I have a class called Projects export class Projects { project_id: number; project_name: string; category_id: number; project_type: string; start_date: Date; completion_date: Date; working_status: string; project_info: string; area: string; add ...

replace specific elements for cloze deletion evaluation

Consider this scenario: There are many reasons to succeed. (consisting of more than 5 words) phrases = ['There', 'are', 'many', 'reasons', 'to', 'succeed'] flashcards_count = ceil(len(phrase) / 3 ...

Exploring the equality of objects in NodeJS

Currently, we are in the process of creating tests for a program. Our goal is to develop a functional test that validates whether the output of the program aligns with certain expectations. The data returned from the program consists of a complex JavaScrip ...

Retrieving information within the iteration

I am facing an issue with connecting to an external server named Pexels in order to retrieve photos from node.js. The problem seems to be related to JavaScript, as Pexels limits the user to download up to 40 pictures per page. https://api.pexels.com/v1/cu ...

Disable automatic browser scroll reset on inline onclick event

Currently, I am utilizing prototype to create an ajax request through an inline onclick on a link. The function is designed to display an element on the page and everything functions properly. However, there is an issue where the browser scroll bar reset ...

Guide to anticipating a boolean prop in my Vue test with mocha/chai?

Utilizing Vue CLI, I am facing an issue with a unit test that checks for a true/false condition. Here is the code snippet in question: describe('The thing', () => { it('must be available.', () => { const available = t ...

What causes the vuetify tag not to render as HTML in the browser?

I ran into a styling issue while using Vuetify in my Nuxt 2 project. Upon inspecting the element in dev tools, I noticed that some Vuetify tags were not being converted to HTML as expected (they were displayed as div class="tag_name"). These unco ...

The background image fails to display properly on the server in Next.js

Hello, I'm currently using NextJs and I have a challenge. I want to set a background image on the body element that is rendered server-side. Below you'll find my code snippets: First, here is my App.js: import BodyStyle from '@components/Bo ...