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

VueJS+Firebase实时数据库:如何仅展示今日录入数据?

解决VueJS + Firebase仅展示今日录入数据的问题

方法一:Firebase端过滤(推荐)

这种方式直接在数据库查询阶段就筛选出今日数据,减少前端传输的数据量,性能更优。

首先计算今日的时间范围边界(以毫秒级时间戳为例,这是Firebase中存储时间最常用的格式):

  • 今日00:00:00的时间戳:new Date().setHours(0, 0, 0, 0)
  • 今日23:59:59.999的时间戳:new Date().setHours(23, 59, 59, 999)

然后结合Firebase的startAt()和endAt()方法,在查询时就锁定今日数据:

修改后的完整代码:

created() {
  // 计算今日时间范围的时间戳
  const todayStart = new Date().setHours(0, 0, 0, 0);
  const todayEnd = new Date().setHours(23, 59, 59, 999);

  const dfRef = db.ref("Colis Requetes");
  // 按created_at排序,并筛选今日数据
  dfRef.orderByChild("created_at")
    .startAt(todayStart)
    .endAt(todayEnd)
    .on("value", (dataSnapshot) => {
      const itemsArray = [];
      dataSnapshot.forEach((childSnapshot) => {
        const childData = childSnapshot.val();
        const childDataKey = childSnapshot.key;
        // 移除原代码中错误的this.Colis = childData; 该行会循环覆盖变量
        itemsArray.push({
          id: childDataKey,
          client_name: childData.client_name,
          client_phone: childData.client_phone,
          colis_type: childData.colis_type,
          payment_method: childData.payment_method,
        });
      });
      // 反转数组实现最新到最旧的排序
      this.Colis = itemsArray.reverse();
    });
}

特殊格式适配

如果你的created_at存储的是ISO日期字符串(如"2024-05-20T14:30:00"),只需调整时间范围的计算方式:

const todayStr = new Date().toISOString().split('T')[0];
const todayStart = `${todayStr}T00:00:00.000`;
const todayEnd = `${todayStr}T23:59:59.999`;

再将上述变量传入startAt()和endAt()即可。

方法二:前端过滤(适合特殊场景)

如果因为权限或其他限制无法在Firebase端过滤,可以在获取全量数据后,在前端筛选今日数据:

created() {
  const todayStart = new Date().setHours(0, 0, 0, 0);
  const todayEnd = new Date().setHours(23, 59, 59, 999);

  const dfRef = db.ref("Colis Requetes");
  dfRef.orderByChild("created_at").on("value", (dataSnapshot) => {
    const itemsArray = [];
    dataSnapshot.forEach((childSnapshot) => {
      const childData = childSnapshot.val();
      const childDataKey = childSnapshot.key;
      // 判断当前数据是否属于今日
      if (childData.created_at >= todayStart && childData.created_at <= todayEnd) {
        itemsArray.push({
          id: childDataKey,
          client_name: childData.client_name,
          client_phone: childData.client_phone,
          colis_type: childData.colis_type,
          payment_method: childData.payment_method,
        });
      }
    });
    this.Colis = itemsArray.reverse();
  });
}

提示

  • 优先使用方法一,尤其是数据量较大时,能有效减少带宽消耗和前端处理压力。
  • 原代码中的this.Colis = childData;属于错误逻辑,会在循环中反复覆盖变量,已在修改后的代码中移除。

内容的提问来源于stack exchange,提问作者Stéphane Konan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 10:36:29