0

I have some products that I have created an array for showing them with VueJS & every product that user chooses goes to a list and every time that clicks on the products, It will increment the "Count" value. Every "Count" value times to the "Price" & writes "Total Price", But this "TotalPrice" is for just a product. So my question is that how can I plus all "TotalPrice" from all products to show the user Total Price ? I should o that with "For Loop" ?

Persons: [
    {Name: 'Ali', Family: 'Bahaari', Age: 20, Count: 0, Price: 200},
    {Name: 'Akbar', Family: 'Jahan', Age: 30, Count: 0, Price: 2500},
    {Name: 'Amir', Family: 'Pirozi', Age: 40, Count: 0, Price: 500},
    {Name: 'Reza', Family: 'Khosravi', Age: 50, Count: 0, Price: 100}
]

<tr v-for="Active in Activated">
    <td>{{ Active.Name }}</td>
    <td>{{ Active.Family }}</td>
    <td>{{ Active.Age }}</td>
    <td>{{ Active.Count }}</td>
    <td>{{ Active.Price }}</td>
    <td>{{ Active.Count * Active.Price }}</td>
</tr>

2 Answers 2

1

Define a computed property and count total sum in it:

computed : {
    totalPrice(){ return this.Activated.reduce((accumulator,currentValue) => accumulator + currentValue.Count * currentValue.Price)
}

Then use it in template like any other variable: {{ totalPrice }}

Sign up to request clarification or add additional context in comments.

1 Comment

computed property, to be accurate.
0

Here is the example

http://jsbin.com/xumugemiza/edit?html,js,output

const app = new Vue({

  el: '#app',

  data: {
    persons: [
    {Name: 'Ali', Family: 'Bahaari', Age: 20, Count: 0, price: 200},
    {Name: 'Akbar', Family: 'Jahan', Age: 30, Count: 0, price: 2500},
    {Name: 'Amir', Family: 'Pirozi', Age: 40, Count: 0, price: 500},
    {Name: 'Reza', Family: 'Khosravi', Age: 50, Count: 0, price: 100}
    ]
  },

  computed: {
     total() {
       let total = 0
       this.persons.forEach(person => total += person.price )
       return total
     }
  }

})

5 Comments

Why filter? Why not forEach?
No special reason, will edit it.In case of performances forEach should be faster than filter ?
I don't know. Maybe it's faster. Maybe the engine can detect that the returned value is discarded so just runs foreach instead.
As I know the normal for loop is faster than this "functional" methods - map, reduce, filter, forEach etc.But not sure too, if there is any difference between forEach and filter in performance case
That really doesn't make any significant difference, use the one you like :) for..of might be preferred when the collection is not an array but an iterable interface. Otherwise use the one that looks better in code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.