【问题标题】:How to plus all the values of a same index in JS array with VueJs如何使用 VueJs 将 JS 数组中相同索引的所有值相加
【发布时间】:2017-01-25 10:29:01
【问题描述】:

我有一些产品,我创建了一个数组,用于使用 VueJS 显示它们,用户选择的每个产品都会进入一个列表,每次点击产品时,它都会增加“计数”值。每个“计数”值乘以“价格”并写入“总价格”,但这个“总价格”只是一个产品。所以我的问题是,我怎样才能加上所有产品中的所有“TotalPrice”来向用户显示 Total Price ? 我应该用“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>

【问题讨论】:

    标签: javascript vue.js vuejs2


    【解决方案1】:

    定义一个computed 属性并计算其中的总和:

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

    然后像任何其他变量一样在模板中使用它:{{ totalPrice }}

    【讨论】:

    • computed 属性,准确地说。
    【解决方案2】:

    这是一个例子

    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
         }
      }
    
    })
    

    【讨论】:

    • 为什么是filter?为什么不forEach
    • 没有特殊原因,会编辑它。如果性能 forEach 应该比 filter 快?
    • 我不知道。也许它更快。也许引擎可以检测到返回的值已被丢弃,因此只需运行 foreach 即可。
    • 据我所知,正常的for 循环比这种“功能性”方法更快——map、reduce、filter、forEach 等。但也不确定,forEach 和 filter in 之间是否有任何区别业绩案例
    • 这真的没有任何显着的区别,使用你喜欢的那个:) 当集合不是数组而是可迭代接口时,for..of 可能是首选。否则使用在代码中看起来更好的那个。
    猜你喜欢
    • 2017-09-29
    • 1970-01-01
    • 1970-01-01
    • 2021-08-19
    • 2019-02-17
    • 2023-04-06
    • 1970-01-01
    相关资源
    最近更新 更多