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

如何在Vue.js中统计数组对象不同status属性的数量?

实现方案

可以通过计算属性实时统计订单状态的数量,计算属性会随orders数据变化自动更新,适配这类动态统计场景。

步骤1:添加统计逻辑的计算属性

在Vue组件的computed选项中,用数组遍历方法实现状态统计:

<script>
import axios from "axios";
export default {
  data() {
    return {
      orders: [], // 初始化为空数组,避免null引发遍历报错
    };
  },
  created() {
    axios.get("http://localhost:5000/api/orders").then((response) => {
      this.orders = response.data;
    });
  },
  computed: {
    orderStats() {
      const stats = {
        delivered: 0,
        otherStatus: {}, // 存储其他状态的数量
        total: 0
      };

      this.orders.forEach(order => {
        const status = order.status.trim(); // 处理可能存在的空格
        stats.total++;
        if (status === "delivered") {
          stats.delivered++;
        } else {
          // 累加其他状态的计数
          stats.otherStatus[status] = (stats.otherStatus[status] || 0) + 1;
        }
      });

      return stats;
    }
  }
};
</script>

步骤2:在模板中展示统计结果

直接在模板中调用计算属性返回的统计数据:

<template>
  <div class="order-stats">
    <p>已交付订单:{{ orderStats.delivered }}</p>
    <p>总订单数:{{ orderStats.total }}</p>
    <h3>其他状态统计:</h3>
    <ul>
      <li v-for="(count, status) in orderStats.otherStatus" :key="status">
        {{ status }}:{{ count }}
      </li>
    </ul>
  </div>
</template>

补充说明

  • 初始化orders为空数组而非null,能避免数据未加载完成时的遍历错误;
  • 用trim()处理状态字符串,可规避接口返回的状态带空格导致的统计偏差;
  • 计算属性orderStats会在orders更新时自动重新计算,确保统计结果实时同步。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 09:27:26