如何计算json对象数组中的值? (在VueJS) [英] How to count values in an json object array? (In VueJS)

查看:56
本文介绍了如何计算json对象数组中的值? (在VueJS)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在一个对象中总结一些属性。
我正在使用VueJS过滤器,结合ES5减少功能来累加数字以获得总数。

i'm trying to sum up a couple of properties in an object. I'm using a VueJS filter, in combination with the ES5 reduce function to add up the numbers to get a total.

嗯,它不适用于此时。有人在乎帮我吗?

Well, it's not working at this moment. Somebody care to help me out?

new Vue({
  el: '.app',
  data: {
    products: [{
      "pid": "37",
      "pname": "Reprehenderit",
      "price": "4.29",
      "amount": "1"
    }, {
      "pid": "45",
      "pname": "Sit",
      "price": "1.00",
      "amount": "4"
    }, {
      "pid": "67",
      "pname": "Omnis",
      "price": "7.00",
      "amount": "2"
    }],
  }
});

Vue.filter('subtotal', function (list, key1, key2) {
    return list.reduce(function(total, item) {
        return total + item.key1 * item.key2
    }, 0)
})

<script src="http://cdnjs.cloudflare.com/ajax/libs/vue/1.0.11/vue.min.js"></script>

<div class="app">
  
  Product example: {{ products[0].pname }}
  
  <br><br>
  
  Total: {{ products | subtotal 'price' 'amount' }}

</div>

推荐答案

在构建vue之后,看起来正在初始化事件处理程序。如果您的事件在被调用时未附加,则会被忽略。

Looks like your event handler is being initialized after the vue is already constructed. If your events aren't attached when they're called they'll be ignored.

此外,您无法像 product.variable 您需要使用产品[变量]

Also, you can't reference your object properties like that product.variable you'll need to use product[variable]

Vue.filter('subtotal', function (list, key1, key2) {
    return list.reduce(function(total, item) {
        return total + item[key1] * item[key2]
    }, 0)
})

new Vue({
  el: '.app',
  data: {
    products: [{
      "pid": "37",
      "pname": "Reprehenderit",
      "price": "4.29",
      "amount": "1"
    }, {
      "pid": "45",
      "pname": "Sit",
      "price": "1.00",
      "amount": "4"
    }, {
      "pid": "67",
      "pname": "Omnis",
      "price": "7.00",
      "amount": "2"
    }],
  }
});

<script src="http://cdnjs.cloudflare.com/ajax/libs/vue/1.0.11/vue.min.js"></script>

<div class="app">
  
  Product example: {{ products[0].pname }}
  
  <br><br>
  
  Total: {{ products | subtotal 'price' 'amount' }}

</div>

这篇关于如何计算json对象数组中的值? (在VueJS)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆