vue for循环中常见问题 之 求和(合计)


例:求后台返回数据
this.dataInfo 中某个字段(item.totalSum)的和,只需添加computed,然后模板中直接可以使用totalSumAll (不需要再data中声明)

computed:{
  totalSumAll(){
    let totalSumAll = 0;
    this.dataInfo.map((item) => {totalSumAll += item.totalSum})
    return totalSumAll
  },
}


添加NAN情况的判断(推荐)
totalSumAll(){
  let totalSumAll = 0;
  this.dataInfo.map((item) => {if(!isNaN(item.totalSum)) totalSumAll += item.totalSum})
  if(isNaN(totalSumAll)){
    return 0
  }
  return totalSumAll
},




原文地址:https://www.cnblogs.com/shuihanxiao/p/10985832.html