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

Search timeout restriction

I have a function that makes a request to the server to retrieve data. Here is the code for it: export default class StatusChecker { constructor() { if (gon.search && gon.search.searched) { this.final_load(); } else { this.make_req ...

Using Vite for creating a production build: A step-by-step guide

Just getting started with Vite and ready to take it into production. I'm wondering how I can create scripts (specifically for docker) to successfully run it in a production environment. The documentation strongly advises against using the preview mod ...

Just starting out with JS, curious if it's possible to transform these circles into diamonds instead

My goal is to transform this animated field of blinking circles into rectangles or diamonds, whichever is easier. Link: http://jsfiddle.net/Jksb5/1/ HTML <canvas id="pixie"></canvas> JS var WIDTH; var HEIGHT; var canvas; var con; var g; va ...

Ways to implement a conditional statement to display a div using JavaScript

Looking for a way to utilize Javascript conditions to toggle the visibility of a div in an HTML5 document? Check out this code snippet below: #demo { width: 500px; height: 500px; background-color: lightblue; display: none; } To set the f ...

When I engage with the input field, it ceases to be in focus

Here is the code I've been working on: https://github.com/Michael-Liendo/url-shortener/blob/main/src/pages/index.js If you want to see the issue for yourself, check it out at: ...

angularjs .reject not executing correctly within the then statement

I'm having trouble identifying the bug in my code. For some reason, $q.defer().reject() isn't functioning correctly. defer.resolve works as expected and even reaches the finally segment, but defer.reject (although it doesn't throw an error) ...

When attempting to retrieve the data from a JSON file using an XMLHttpRequest, the result that is returned is [object object]

I am currently studying JSON and found a helpful guide on w3schools. Here is the code provided in the guide: https://www.w3schools.com/js/tryit.asp?filename=tryjson_ajax The guide also includes a sample JSON file: https://www.w3schools.com/js/json_demo.t ...

Compel the browser to launch a fresh tab

I'm currently working on an app that involves uploading files. One issue I'm facing is that the file system pop up doesn't close after the upload, causing a quarter of the screen to be covered while the test keeps running in the background. ...

I am experiencing an issue where the jquery sleep function is not being executed during

I currently have an Ajax request that is awaiting a response from another process. function checkProcess() { var flag = 0; while (flag === 0) { $.ajax({ url: "cs/CheckForProcess", async: false, success: ...

Flow object with Angular using ng-flow: Existing flow object

Just a quick question that I can't seem to find an answer for on my own or through searching online. Currently, I have a button set up for clicking and uploading files. However, I also want to incorporate drag and drop functionality using the same fra ...

What is the most efficient way to prevent duplicate items from being added to an array in a Vue 3 shopping cart

I currently have a functional shopping cart system, but I am facing an issue where it creates duplicates in the cart instead of incrementing the quantity. How can I modify it to only increment the item if it already exists in the cart? Also, I would like t ...

angular.js watch() method is not functioning properly during a JSON call

I am trying to trigger a method whenever the value of my $http.selectedSong (model value) changes, but for some reason it is not working. Any ideas on why this could be happening?: app.controller('songController', ['$http', function($h ...

The module 'NgAutoCompleteModule' was declared unexpectedly by the 'AppModule'. To fix this issue, make sure to add a @Pipe/@Directive/@Component annotation

Currently, I am attempting to integrate an autocomplete feature into my Angular 2/4+ project. Despite trying various libraries, none of them seem to be working correctly. Each one presents me with a similar error message: Unexpected module 'NgAutoCom ...

Modifying a JavaScript code with document.write(variable)

I am working with a Javascript function function setComparison(data) { var w= window.open('', 'comparison', 'width=600, height=400'); w.document.open(); w.document.write(getComparisonContent(data)); w.document ...

Learning about extracting the route path variable in the node.js Express route.get() function

Why am I encountering a 404-NotFound error in this scenario? var test = require('./routes/test'); app.use('/test', test); router.get('/test', function (req, res, next) { //res.render('/test', { title: 'test ...

What are some effective methods for troubleshooting npm modules?

Typically, the process involves installing React with yarn/npm install react and then using it by importing React from 'react' Imagine you need to debug a React source code, so you clone a GitHub repository. But how do you incorporate this sour ...

How to add an OnClick listener to a cell element in a table built with the Tan

I am currently working on a project using React and trying to implement a table. I want to show an alert when a header cell in the table is clicked, displaying some information. However, I have been struggling to find assistance on adding a click listener ...

What is the reasoning behind placing CDN links at the bottom of the index file?

What is the reason for placing CDN links for AngularJS file at the end of the index page? I initially placed it at the top of the file and it worked fine. Is there a significant difference between these two placements? ...

Enlarging the modal overlay

My Angular/Bootstrap app features a small text area within a modal window that often contains lengthy content exceeding the size of the textarea and modal itself. I am looking to incorporate a button within the modal window that, when clicked, opens a lar ...

What is the best way to compare two date strings with the format dd/mm/yyyy using JavaScript?

When attempting to compare a "Date" type of data with an "Any" type of data, the comparison is not functioning as expected. The date is retrieved in the following code: var today = new Date(); var dd = String(today.getDate()).padStart(2, '0'); v ...