Calculating the total sum in Vuejs when an event is triggered

I am faced with a situation where the price of a product is added to an existing total when a user increases the quantity. However, the problem lies in the fact that even if the user decreases the quantity, the price continues to increase.

Solution

html

<el-input-number style="width: 100%;" ref="amount" v-on:change="amoutChanged($event, row)" v-model="row.amount" :min="1"></el-input-number>

script

data() {
    return {
        subtotal: 0,
    }
},
methods: {
    amoutChanged: function(event, row) {
        console.log('amount row: ', row);
        console.log('amount event: ', event);
        // PROBLEM: the price is always increased regardless of whether the quantity is increased or decreased
        this.subtotal = parseInt(this.subtotal) + parseInt(row.price);
    },
}

https://i.sstatic.net/4rkEJ.png

Results in Console

amount row:  {barcoded: "8995078803078", …}
  amount: (...)
  barcode_id: (...)
  barcoded: "8995078803078"
  price: (...)
  product: (...)

amount event:  2  // This is the input quantity by the user

Challenge

How can we update the total price correctly based on user actions of increasing or decreasing quantity?

Answer №1

I tackled the problem in the following way:

Firstly, I transformed the subtotal property into a computed one and used .reduce() to sum up the values. Additionally, I introduced a new property called singlePrice to enable multiplication.

var Main = {
  data() {
    return {
      serial_numbers: [{
        barcode_id: '45634643',
        product: 'dfgs546',
        amount: 1,
        price: 100,
        singlePrice: 100,
      },{
        barcode_id: '23523fd',
        product: 'rgdg46546',
        amount: 1,
        price: 100,
        singlePrice: 100,
      },{
        barcode_id: 'fdghdh',
        product: '345634643',
        amount: 1,
        price: 100,
        singlePrice: 100,
      }],
      total: 0,
      num1: 1
    };
  },
  computed: {
     subtotal(){
    
       return this.serial_numbers.reduce((a,v)=> a + v.price,0)
     }
  },
  methods: {
    addRow() {
    var barcodes = document.createElement('tr');
      this.serial_numbers.push({
        barcode_id: '675476547',
        product: 'hjfgj67',
        amount: 1,
        price: 100,
        singlePrice: 100,
      });
    },
    removeElement: function(index) {
      this.serial_numbers.splice(index, 1);
    },
    amountChanged($event, index){
       let amount = $event;
       this.serial_numbers[index].amount = amount;
       this.serial_numbers[index].price = this.serial_numbers[index].singlePrice * amount;
    }
  }
};
var Ctor = Vue.extend(Main)
new Ctor().$mount('#app')
@import url("//unpkg.com/vue/lib/theme-default/index.css");
<script src="//unpkg.com/vue/dist/vue.js"></script>
<script src="//unpkg.com/vue/lib/index.js"></script>
<div id="app">
  <table class="table table-bordered table-striped table-hover">
    <thead>
      <tr>
        <td><strong>Serial Number</strong></td>
        <td><strong>Product</strong></td>
        <td><strong>Amount</strong></td>
        <td><strong>Price</strong></td>
        <td width="50"></td>
      </tr>
    </thead>
    <tbody>
      <tr v-for="(row, index) in serial_numbers" :key="index">
        <td>
          <el-input ref="barcoded" v-model="row.barcode_id"></el-input>
        </td>
        <td>
          <el-input ref="product" v-model="row.product" readonly></el-input>
        </td>
        <td>
          <el-input-number style="width: 100%;" ref="amount" @change="amountChanged($event, index)" v-model="row.amount" :min="1"></el-input-number>
        </td>
        <td>
          <el-input ref="price" v-model="row.price" readonly></el-input>
        </td>
        <td>
          <el-link :underline="false" type="danger" v-on:click="removeElement(index);" style="cursor: pointer"><i class="fa-2x el-icon-remove"></i></el-link>
        </td>
      </tr>
    </tbody>
  </table>
  <div>
    <el-button type="primary" class="button btn-primary" round @click="addRow"><i class="el-icon-circle-plus"></i> Add row</el-button>
  </div>

  <el-row :gutter="10">
    <el-col :span="8" :offset="16">
      <table class="table table-bordered table-striped table-hover">
        <tbody>
          <tr>
            <th width="100"><strong>Sub total</strong></th>
            <td>
              {{subtotal}}
            </td>
          </tr>
          <tr>
            <th width="100"><strong>Total</strong></th>
            <td>
              {{total}}
            </td>
          </tr>
        </tbody>
      </table>
    </el-col>
  </el-row>
</div>

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

What is the reason for Rich file manager to include filemanager.config.json instead of simply adding an image to the text

I have integrated Rich File Manager with Laravel 5.3.20 using the default configuration provided below: Javascript <script> CKEDITOR.replace( 'textarea', { filebrowserBrowseUrl: '{!! url('gallery/index.html& ...

Learn how to manipulate data within a MongoDB database schema using Node.js and Mongoose: inserting, saving, and updating records

When inserting data into the MongoDB schema presented below, make sure that Employee name, Project name, and client name can be the same, but the employee ID must be unique. Duplicate entries are not allowed. var StatusSchema = new mongoose.Schema({ ...

Using Regular Expressions in an ExpressJS Router

When working with ExpressJS, is there a way to combine the following routes into one using RegEx? app.get(/^\/blog(?:\/p(\/\d+)?)?$/, blog.list); ...

Adjust the number of columns based on the minimum screen resolution using columnizer

Currently, I am utilizing the columnizer jQuery plugin to divide my content into columns on a responsive website with a fluid width container. I have implemented different JavaScript functions based on the minimum screen resolutions, similar to CSS media q ...

JavaScript - Assigning a class to an element based on an array

I am facing a challenge where I need to assign classes from an array to an element in sequential order. The issue is that once I reach the end of the array, I do not know how to loop back to the beginning and start over. Here is my current code: var bac ...

non-concurrent in Node.js and JavaScript

I'm a beginner in the world of NodeJS and I have a question that's been bugging me. Node is known for its asynchronous nature, but JavaScript itself also has asynchronous features (like setTimeout). So why weren't concepts like Promise intr ...

In Vue2, you can utilize $ref to retrieve information from a child component and transfer it into the parent component's data

Trying to access child components' data in Vue2 and move it into the parent component's data without triggering an event. Saving count:20 from the child component into the parent component in the example below. Please let me know if there are any ...

Running a series of functions consecutively with JQUERY

Currently, I am facing an issue with using an ajax method .load to replace the content of a div. The library I am working with does not allow me to replace the content of a div as some functions continue to run in the background. To overcome this challeng ...

Vue for Number Crunching

Learning vueJS is quite new to me. I am attempting to capture two input values, add them together, and display the result. I have encountered a strange issue where when subtracting number1 from number3, multiplying number1 with number2, or dividing number ...

Generating documents in Word or PDF format using PHP and Angular data

My goal is to generate a Word document using PHP for which I found a solution involving the use of headers. header("Content-type: application/vnd.ms-word"); header("Content-Disposition: attachment;Filename=output.doc"); Initially, this method worked well ...

Connect data dynamically to the p-table based on columns

I'm facing a challenge in displaying JSON data in a table format, and I'm looking for a way to accomplish this using p-table. When looping through the data, I'm noticing duplicate records in the rows. Can anyone guide me on how to achieve th ...

Warning from React 17: Unexpected presence of <a> tag inside <div> tag in server-rendered HTML

I've checked out the existing solutions and still can't seem to make it work. components/NavBar.tsx import { Box, Link } from "@chakra-ui/react"; import { FunctionComponent } from "react"; import NextLink from "next/link ...

An issue arises when attempting to utilize URL parameters within a loader

In my React project, I am utilizing React-Router. The code for my movie page is as follows: import React from "react"; import axios from 'axios' export async function loader({ params }) { const movieId = params.movieId; const mov ...

Advantages of incorporating lazy loading in a Vue Single Page Application:

What level of realistic benefit can be expected from lazy loading in a Vue application using Vue-router, Vuex, and many components to improve initial load times in an SPA? In comparison to minifying and bundling code (in this case, with gulp), do the perf ...

"Is there a way to automatically delete items from a v-for loop after a

Can someone advise me on the best way to add, remove, and restart a timer for a messaging feature? The goal is to automatically delete messages 5 seconds after they are sent, but pause the deletion if the user hovers over the message. Messaging Code & ...

Retrieve information from a JSON API on one server and showcase it on an HTML page hosted on a different server

I have a situation where I need to transfer data from one project (Project1) to another project (Project2). To achieve this, I decided to convert the Project1 data stored in a database into a JSON API and then call it using an HTML page from Project2. Howe ...

Steps to creating an Ajax JQuery in WordPress with promises

Currently, I am in the process of developing a custom Wordpress Google Maps plugin. This plugin fetches locations from a database using Ajax and returns an XML file that is then handled by a Javascript script to display them on a Google Map. Everything is ...

Accessing Facebook through the React create app login

I recently developed a React Webapp using the create-react-app module. My current challenge involves integrating Facebook login, but I'm encountering some obstacles. I am unsure about where to incorporate the Facebook JavaScript SDK asynchronously to ...

Modifying state within useEffect while also including the redux value as a dependency array

I am facing an issue with my Redux array and the dependency array in my useEffect. The problem arises when I store the value of the Redux array in a variable using useSelector, which is then used as a dependency in my useEffect. The logic inside the useE ...

Is there a way in MVC3 / .net4 to convert a JSON formatted JavaScript array into a C# string array?

I am facing a challenge with my MVC3/.Net service where it is receiving arguments in the form of a JSONified Javascript array. I want to convert them into a C# array of strings. Is there a built-in solution available for this task, or do I need to create ...