You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue.js如何在v-for循环外最简计算userList的balance余额总和

Vue实现用户余额总和的最简方案

核心实现思路

直接使用Vue自带的**计算属性(computed)**实现,计算属性会自动响应userList的内容变化,余额更新时总和会自动同步,不需要手动监听数组变化。

修改步骤

1. 给Vue实例新增计算属性

在现有Vue实例中添加computed配置项,定义总和计算逻辑,注意你的balance是字符串类型,需要先转成数值再累加:

const app = new Vue({
  el: '#app',
  data: {
    userList: [{
        id: 1,
        name: "Prem",
        gender: "male",
        balance:'3522'
      },
      {
        id: 2,
        name: "Chandu",
        gender: "female",
        balance:'2762'
      },
      {
        id: 3,
        name: "Jong",
        gender: "female",
        balance:'2000'
      },
      {
        id: 4,
        name: "Steew",
        gender: "male",
        balance:'2000'
      },
      {
        id: 5,
        name: "Abdollah",
        gender: "female",
        balance:'2000'
      },
      {
        id: 6,
        name: "Jerry",
        gender: "male",
        balance:'1500.5'
      }
    ]
  },
  // 新增计算属性
  computed: {
    totalBalance() {
      // reduce累加,初始值为0,转成浮点数后求和,保留2位小数
      return this.userList.reduce((total, user) => total + parseFloat(user.balance), 0).toFixed(2)
    }
  }
});

2. 修改HTML表格底部的总和展示位

直接在tfoot的Total后引用计算属性即可,同时注意修复你现有代码中未闭合的td标签:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.js"></script>
<script src="https://unpkg.com/vue-router@2.0.0/dist/vue-router.js"></script>

<div id="app">
<table class="table table-hover table-striped table-bordered">
        <thead>
        <tr>
            <th>Name</th>
            <th>Gender</th>
            <th>Price</th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="(user, i) in userList" class="position-relative">
            <td>{{ user.name }}</td>
           <td>{{ user.gender }}</td>
            <td>{{user.balance}}</td>
        </tr>
        </tbody>
          <tfoot>
          <tr>
          <td>total number of records: {{userList.length}}</td>
          <td></td>
          <td>Total: {{ totalBalance }}</td>
          </tr>
           </tfoot>
    </table>
</div>

补充说明

  • 用toFixed(2)是为了统一保留两位小数,符合金额的展示规范,如果不需要固定小数位数可以去掉该方法。
  • 你原代码中表头的Pice是拼写错误,已修正为Price,不需要可以改回。

内容的提问来源于stack exchange,提问作者Selaminko Elam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 18:48:03