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

Vue2中如何按日期过滤响应数据?(本月/本年/本周数据)

Vue2 按日期筛选数据(本月/本年/本周)解决方案

没问题,我来帮你搞定这个日期筛选的需求!咱们先把完整的计算属性代码写出来,再逐个拆解每个筛选逻辑:

computed: {
  filteredData() {
    const now = new Date();
    const currentYear = now.getFullYear();
    const currentMonth = now.getMonth() + 1; // 注意:getMonth()返回0-11,所以要+1转成1-12的常规月份格式

    switch(this.duration) {
      case 'year':
        // 筛选本年数据:匹配日期的年份与当前年份一致
        return this.data.filter(item => {
          const itemYear = new Date(item.date).getFullYear();
          return itemYear === currentYear;
        });
      
      case 'month':
        // 筛选本月数据:年份和月份都要与当前匹配
        return this.data.filter(item => {
          const itemDate = new Date(item.date);
          const itemYear = itemDate.getFullYear();
          const itemMonth = itemDate.getMonth() + 1;
          return itemYear === currentYear && itemMonth === currentMonth;
        });
      
      case 'week':
        // 筛选本周数据:默认以周一为一周起始,计算本周的时间范围
        const startOfWeek = new Date(now);
        // 计算本周一的日期:如果当前是周日,需要往前推6天到周一
        startOfWeek.setDate(now.getDate() - now.getDay() + (now.getDay() === 0 ? -6 : 1));
        startOfWeek.setHours(0, 0, 0, 0); // 重置时分秒,确保从当天0点开始
        
        const endOfWeek = new Date(startOfWeek);
        endOfWeek.setDate(startOfWeek.getDate() + 6); // 本周日的日期
        endOfWeek.setHours(23, 59, 59, 999); // 设置为当天最后一刻,避免漏掉当日数据
        
        return this.data.filter(item => {
          const itemDate = new Date(item.date);
          return itemDate >= startOfWeek && itemDate <= endOfWeek;
        });
      
      default:
        // 默认返回全部数据
        return this.data;
    }
  }
}

关键逻辑拆解

1. 本年筛选

通过new Date(item.date).getFullYear()提取每条数据的年份,直接和当前年份currentYear对比,相等则保留该条数据。

2. 本月筛选

需要同时匹配年份和月份:注意JavaScript的getMonth()方法返回0-11(0对应1月),所以要加1转成1-12的常规月份格式,再和当前月份currentMonth做双重匹配。

3. 本周筛选

这里默认把周一作为一周的起始(如果需要以周日为起始,可以调整计算逻辑):

  • 先计算本周一的日期:通过当前日期减去当前是周几的数值,再做周日的特殊处理(周日getDay()返回0,需要额外减6天)。
  • 再计算本周日的日期:在周一基础上加6天,并设置时分秒为当天最后一刻,确保不会漏掉当日的所有数据。
  • 最后判断数据的日期是否落在周一到周日的时间范围内。

使用提示

你只需要把按钮的点击事件和this.duration绑定即可:比如点击「月份」按钮时,把this.duration设为'month',计算属性就会自动返回本月的数据。另外要确保接口返回的date字段是合法的日期格式(比如你提供的YYYY-MM-DD),避免Date对象解析出错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 07:58:03