vue.js代码中的按功能分组求和

时间:2019-01-18 16:26:32

标签: vuejs2 lodash

我正在尝试在vuejs代码上使用groupBy和sumBy用lodash求和。我也尝试这个链接 https://codepen.io/cmtliton/pen/bjNNNq?editors=1010

new Vue({
  el: '#app',
  data () {
    return {
      SaleReports : [
        {
		ProductId: "PVk2WIKjZJ",
		quantity: 2,
		MRP: 15
	},
	{
		ProductId: "PQ_bCOJx5h",
		quantity: 2,
		MRP: 250
	},
	{
		ProductId: "PVk2WIKjZJ",
		quantity: 1,
		MRP: 15
	},
	{
		ProductId: "PQ_bCOJx5h",
		quantity: 1,
		MRP: 250
	}
      ],
      SummationReports : []
    }
  },
  computed: {
    getSummationSalesReport () {
      return _(this.SaleReports)
        .groupBy('ProductId')
        .map((g, ProductId) => {
          return {
            ProductId: ProductId,
            quantity: _.sumBy(g, 'quantity'),
            MRP: _.sumBy(g, 'MRP' * 'quantity')
          }
        })
        .values()
        .value()
    }
  },
  methods: {
    
  },
  created () {
    this.SummationReports = this.getSummationSalesReport
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <pre>{{$data | json}}</pre>
</div>

我需要如下结果:

"SummationReports": [
    {
      "ProductId": "PVk2WIKjZJ",
      "quantity": 3,
      "MRP": 750
    },
    {
      "ProductId": "PQ_bCOJx5h",
      "quantity": 3,
      "MRP": 45
    }
  ]

1 个答案:

答案 0 :(得分:0)

You can use the computed property directly in the view - no need to assign it manually to the data.

In addition, _.sumBy() accepts only a single property. Get the quantity using _.sumBy(), and for the MRP, get the 1st item MRP and multiply it with the quantity sum.

new Vue({
  el: '#app',
  data() {
    return {
      SaleReports: [{"ProductId":"PVk2WIKjZJ","quantity":2,"MRP":15},{"ProductId":"PQ_bCOJx5h","quantity":2,"MRP":250},{"ProductId":"PVk2WIKjZJ","quantity":1,"MRP":15},{"ProductId":"PQ_bCOJx5h","quantity":1,"MRP":250}],
    }
  },
  computed: {
    SummationReports() {
      return _(this.SaleReports)
        .groupBy('ProductId')
        .map((g, ProductId) => {
          const quantity = _.sumBy(g, 'quantity')
          
          return ({
            ProductId: ProductId,
            quantity,
            MRP: quantity * _.get(g, '[0].MRP'),
          })
        })
        .values()
        .value()
    }
  },
})
/** hide the annoying vue dev mode messages **/
.as-console-wrapper {
  display: none !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <pre>{{ SummationReports }}</pre>
</div>