Alexander Alexander - 3 months ago 29
Javascript Question

vue.js sum of keys after applying filterBy

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

I am new to
vue.js
and struggling to find a right way of making 'Total Coins' value.

For example : Total sum of coins is equal '30', so when i enter the letter "z" in to the filter box, the filter is applied, "Client Z" and "Client Z2" only should be visible and the total of coins would be equal '15'.

What is the right way to do it in
vue.js
?

What have i done before asking ?


  • I have done this using listener on
    filterQuery
    change , but this is not efficient as more filters may be added.

  • Have tried to add
    v-model
    to the
    v-for
    loop so i can get filtered results in a dedicated variable, but this does not seem to update the model.


Answer

Why not this

https://jsfiddle.net/f5d16skc/

computed: {
    filteredClients: function () {
    return this.clients.filter(c => c.name.indexOf(this.query) !== -1)
  },
  totalCoins: function () {
    return this.filteredClients.reduce((a, b) => a + b.coins, 0)
  }
}

Remember: never use filters in v-for! It's deprecated.