Determine the total of values that are added dynamically using vuejs

When a specific option is selected in the first column of the last row, I am dynamically adding a new row to a table that includes selects and inputs.

This functionality can be seen at https://jsfiddle.net/zgykgery/. When 'Service' is selected, a new row is added with the total price calculated based on the service price, default 10% discount, and amount.

The method I currently use to extract the service price seems cumbersome: :value="item.id+'|'+item.price" However, it works. Now, I need help figuring out how to loop through all rows, sum up the prices without discounts, calculate the total discount, and then determine the full price including the service price and discount.

I understand I should utilize computed properties or watchers for this task, but I'm unsure how to proceed.

How can I compute the sum of these values within the table and display them in a smaller table below?

Update

As a newcomer to Vue.js, I attempted to achieve this using computed properties, but unfortunately, I was unsuccessful. Below is my attempt:

// Your JavaScript code here 
// Your CSS code here
<script src="//unpkg.com/vue/dist/vue.js"></script>
<script src="//unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="630c050c040c071dfa030f26340814081419">[email protected]</a>/lib/index.js"></script>
<div id="app">
  <template>
    // Your HTML code here
  </template>
</div>

In an updated version of the fiddle found at https://jsfiddle.net/zgykgery/21/, the total price still remains empty after changes are made.

Answer №1

In accordance with @Roy J's suggestion, utilize a computed function to retrieve the results of your calculation. This way, the values will automatically update whenever the data within item changes.

UPDATE: A straightforward method is more suitable in scenarios where a v-for loop is being used.

methods: {
    priceID (item) {
        return item.id + '|' + item.price
    }
}

To implement this, simply use it within your Vue code like so:

<tr v-for="(row, index) in rows_top">
  <td>
    <el-select placeholder="Select" filterable="filterable" @change="addRow(row, index)" v-model="row.service">
      <el-option v-for="item in services" :key="item.id" :label="item.name" :value="priceID(item)"></el-option>
    </el-select>
  </td>
  ...

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

"Encountered an error when using the pop method on a split function: 'undefined is not

I am working with an array of filenames called ret, and I need to extract the extension of each file name. var cList=""; var fName=""; var ext=""; for(var i=0;i<=ret.length-1;i++){ fName=ret[i]; ext=fName.s ...

Utilizing AngularJS to Extract JSON Data from Gzipped Files Stored Locally via Ajax

Currently, I am attempting to retrieve and read a JSON file that is stored in data.gz using AngularJS's $http service. However, when I make the request, all I get back are strange symbols and characters as the response. My application is being run loc ...

Alter the functionality of the input element that has a tag of 'multiple'

I am encountering an issue with a form that allows users to upload multiple photos. When selecting multiple files at once, everything works as expected. However, if a user wants to add images one by one, each new addition deletes the previous file due to t ...

The backward navigation in Chrome leads to an incorrect webpage

With my current use of NodeJS, I have a function in place that requests content from the server and displays it on the browser as a complete HTML page. However, there seems to be an issue with Chrome where if I follow these steps, the original page is ski ...

Struggling to vertically align elements within iron-pages

Struggling to vertically center the content within iron-pages (nested in a paper-drawer-panel). Check out the code snippet below: <paper-drawer-panel id="drawerPanel" responsive-width="1280px"> <div class="nav" drawer> <!-- Nav Conte ...

Error: The signature for uploading S3 Knox Node.js does not match

For the past several days, I've been attempting to upload a file named message.txt to AWS S3 using knox and node js. However, I continuously encounter an error stating that the signature doesn't match. Here is my code snippet in node js (since ...

What are the steps to execute Mike Bostock's D3 demonstrations?

I've been attempting to run Mike Bostock's See-Through Globe demonstration, but I encountered issues with the correct referencing of his json files when attempting to replicate it locally. The problem stems from this particular line of code: d3. ...

how to set up automatic login for a user after changing their password using passport-local-mongoose

Trying to automatically log in a user, but encountering an issue with the current 'update' function that looks like this exports.update = async (req, res) => { const user = await User.findOne({ resetPasswordToken: req.params.token, re ...

I am encountering issues with my PostCSS plugin not functioning properly within a Vue-cli 3 project

I developed a custom postcss plugin that was working perfectly according to the postcss guidelines until I tried to implement it in a real project. For reference, here's the plugin on GitHub My goal is to integrate it into a Vue-cli app using Webpac ...

Retrieving data from JSON by value compared to arrays

In this scenario, an ajax request fetches a json response that contains a product_id along with other values in each object. I currently have a PHP variable that holds an array of product objects (in a Laravel collection) and I want to avoid querying them ...

Avoid inputting various symbols into the select2 field

I recently upgraded my select input to use select2: <select id="indivCitizen" multiple="multiple"> <option value=""></option> </select> To fetch data dynamically and enhance user experience: $(doc ...

Retrieve the previous value of the selection change with the Mat Select function

In my current project, I have a form with a mat-select dropdown. Whenever the user makes a selection, a dialog pops up to confirm the choice. However, I am facing an issue: The selectionChange() event is triggered when the value changes and provides the n ...

Prevent clicking on form until setInterval has been cleared using React useEffect

Here is a link to a sandbox replicating the behavior: sandbox demo I have integrated a hook in a React component to act as a countdown for answering a question. React.useEffect(() => { const timer = setInterval(() => { setTimeLeft((n ...

How can I prevent ng-blur from triggering when ng-readonly is set to true in AngularJS?

I am currently working with AngularJS and have run into an issue when combining ng-blur with ng-readonly. Even though ng-readonly is set to true, ng-blur still triggers (if the input field is clicked and then somewhere else is clicked). In this example, n ...

Tips for preserving the state of the Material-UI AutoComplete during component re-renders?

Currently, I am utilizing the Material-UI v4 AutoComplete component along with the renderOption prop in order to display a checkbox item option. The issue arises when the onChange event occurs and updates a hook in the parent component causing a re-rende ...

Retrieve items from a JSON file using Ionic framework's $http.get method

Issue with Console: SyntaxError: Unexpected token { in JSON at position 119 Xcode controller: str="http://www.website.com/user-orders.php?e="+$scope.useremail; $http.get(str) .success(function (response){ $scope.user_orders = response; ses ...

The 'newPassword' must be included as a String parameter

SOLVED The issue has been resolved. It was found that the backend required data in param format, so the form sent by Vue was changed to param instead of data! I am currently working on a password change page. I encountered an error stating that there was ...

Is there a way to update a state only if it matches the corresponding ID?

updateItem = (id) => { this.setState( { lanche: [ { id: id, updateItem: true }] } ) } Instead of updating all items in the array, I want to specifically target and edit the item with a m ...

Implement a personalized Laravel Dusk selector with the attribute data-dusk

In the world of Laravel Dusk, the default selector hunts for the dusk="something" attribute in your HTML. If you want to dive deeper into this topic, check out this resource. However, when it comes to compatibility with Typescript for React/Vue, ...

Bug causing connection issues in Node.js when dealing with IP redirection

I recently encountered an issue with NodeJS while using a kafka node on a node-red instance installed on my RPI3. Let me paint you the scenario: I have a cluster set up with a functioning Kafka instance. The machine hosting the Kafka broker has a private ...