Calculating the total sum of values from keys, post applying the filterBy method

HTML:

<div id="app">
  <h1>{{title}}</h1>
  <form id="search">
    Filter <input name="query" v-model="filterQuery">
  </form>
  <table>
    <tr v-for="client in clients | filterBy filterQuery">
      <td>{{ client.name }}</td>
      <td>{{ client.coins }}</td>
    </tr>
  </table>
  <b>Total Coins: ???</b>
</div>

JS:

var app = new Vue({
  el: "#app",
  data: {
      title: "Demo app",
      clients: [
        {name: "client X",  coins:  5},
        {name: "client Y",  coins: 10},
        {name: "client Z",  coins:  3},
        {name: "client Z2", coins: 12}
      ]
  }
});

Fiddle Here

Exploring the possibilities of vue.js is a new adventure for me. I'm currently facing a challenge in calculating the 'Total Coins' value based on filtering.

For instance, the total sum of coins is 30. If I input the letter "z" in the filter box, the filter should only display "Client Z" and "Client Z2" with a total of coins equal to 15.

What would be the most efficient approach to achieve this in vue.js?

Before seeking assistance, I attempted the following:

  • Implemented a listener on filterQuery change, but this method is not scalable with additional filters.
  • Tested adding v-model to the v-for loop to get filtered results in a separate variable, but the model did not update as expected.

Answer №1

Why not give this a try

https://jsfiddle.net/f5d16skc/

calculated: {
    updatedCustomers: function () {
    return this.customers.filter(c => c.name.indexOf(this.query) !== -1)
  },
  totalMoney: function () {
    return this.updatedCustomers.reduce((a, b) => a + b.money, 0)
  }
}

Just a reminder: avoid using filters in v-for! It's not recommended.

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

Updating the route when submitting input value using React-Router

I designed a top bar menu that includes a navbar component along with a form component featuring a text input. This form is responsible for changing the state of the app component, which serves as the parent to the navbar. The navbar, located outside the r ...

"Implementing a click event on a dynamically generated element is triggering the event for all of its parent elements

I have a task to generate a dynamic table with data retrieved from the server. Each row in the table contains a tag that I am trying to link to a click event. The code snippet below demonstrates how the dynamic table is created: function ProcessResponse ...

What is the best way to apply CSS modifications to sibling elements that are related?

I have several parent div elements with pairs of button and div child elements. My goal is to apply changes to the corresponding div when a button is clicked. For example, clicking Button 2 should only affect toast 2. However, I am facing an issue where o ...

Arranging Data in Arrays using Angular 4 GroupBy Feature

I'm working with an array structured like this: var data = [ { student: "sam", English: 80, Std: 8 }, { student: "sam", Maths: 80, Std: 8 }, { student: "john", English: 80, Std: 8 }, { student: "j ...

Patience is key when it comes to waiting for a function to finish before moving on to the next step

I'm delving into the world of node js and currently immersing myself in the concepts of promises and async/await. Here's a code snippet I've been experimenting with, but I can't quite figure out how to ensure that the code waits until t ...

"Exploring ways to reattempt a route request upon encountering the $stateNotFound event within AngularUI Router

Managing a large AngularJS application can be quite challenging when it comes to splitting it into functional modules. Currently, all the modules are loaded on the initial page load as they are bundled into a single JavaScript file. However, I am looking t ...

Angular: Handling window resizing events in your application

To handle window resize events in a non-angular application, we typically use the following code: window.onresize = function(event) { console.log('changed'); }; However, in angular applications, it's not recommended to directly acc ...

Passing the output of a function as an argument to another function within the same HTTP post request

I have a situation where I am working with two subparts in my app.post. The first part involves returning a string called customToken which I need to pass as a parameter into the second part of the process. I'm struggling with identifying where I m ...

Ways to dynamically fetch data by merging the response outcome with a dynamic parameter from the route in Vue.js

For the first time, I have been tasked with dynamically retrieving object parameters from the URL parameter. I am aware that I can use this.$route.params.[somelink-parameter] to obtain the URL parameter, and I understand how to retrieve and store the respo ...

Does client-side JS/Angular have an HTTP Connection Timeout feature?

I'm currently using Angular's HttpClient to send HTTP requests and I want to set a specific timeout for them. Although I am aware that I can utilize HTTPInterceptors and include a timeout in RxJS operators, these settings apply to the entire req ...

Struggling to integrate font-awesome into my Vue.js project

Observation: The stars should be displayed using the Font Awesome font. Issue: An error font is being displayed instead of Font Awesome, indicating that it is not being loaded properly. Hello. I am encountering problems with including Font Awesome in my p ...

Tips for extracting HTML tags directly from JSON data

In my dataset, I have a JSON illustration [{ "Field1": "<header class=\"main-header dark-bg\">\n\t\t<div class=\"row\">\n\t\t\t\t<div class=\"col-xl-3\">\n< ...

Initiating an audio call exclusively via SimpleWebRTC

I'm currently utilizing a jQuery plugin for WebRTC found here. My goal is to initiate an audio call only, but I am struggling to find a function within the plugin that allows for this. The code snippet I am using with autoRequestMedia set to false is ...

Guide on building a "like" button using a Node.js Express application

I am in the process of developing a website using node, express, and mongodb. I am facing an issue with passing a variable value from my ejs file to the server side. Can someone help me solve this problem? Here is what I have attempted so far: Example Ht ...

How to display an array with JSON objects in Angular 4

Looking to display specific data from an array in my .html file that originates from my .ts file: myArray: ["03/05/2018", "2:54", "xoxo", "briefing", "your", [{ "Id": "1", "Time": "20:54", "Topic": "mmmmm", "GUEST1": { "Role": "HS" ...

Troubleshooting: Issues with jQuery.on method functionality

I'm currently using jQuery version 1.9.1 and I have a situation where I need to perform an action on a dynamically added td element. I attempted to utilize the jQuery.on function, however my code is not being triggered. Can someone please provide some ...

What is the exact functioning of the Array.push() method in Javascript?

During my online CS class, we covered the topic of how Arrays and memory work. The teacher used C as an example to explain that you cannot add extra elements to a full Array. As someone who started with JavaScript, I found it interesting that in JavaScript ...

Keep elements in position when their bottom edge becomes visible while scrolling

This task may appear intricate, but I will do my best to explain it! I want to create a continuous scrolling article display similar to Bloomberg Politics (), but with a slight twist. My idea is to have the current article's bottom edge stick to the ...

At which location within the script should I insert the document.title in order to update the title every xx milliseconds?

I have been working on a script that refreshes certain #id's. Additionally, I would like to update the page title, which involves some flask/jinja2. I've attempted placing document.title = {% block title %} ({{online_num}}) Online Players {% en ...

Infinite dice roller for a six-sided die

Looking for assistance with a School JavaScript assignment focusing on creating a 6-sided dice roller program? Need some guidance on how to approach this task? The program should allow users to choose how many dices to roll, ranging from 1 to 5. The sum o ...