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

如何在Vue.js中按月份筛选WordPress文章?

Vue.js + WP REST API 实现文章月份筛选功能

1. 基础HTML结构

先搭建页面核心交互区域,包含筛选下拉框和文章列表容器:

<div id="app">
  <!-- 月份筛选下拉选择器 -->
  <select v-model="selectedMonth" @change="filterPostsByMonth">
    <option value="">所有月份</option>
    <option v-for="month in uniqueMonths" :key="month" :value="month">{{ month }}</option>
  </select>

  <!-- 筛选后的文章展示区 -->
  <div class="post-list">
    <div v-for="post in filteredPosts" :key="post.id" class="post-item">
      <h3>{{ post.title.rendered }}</h3>
      <p>发布时间: {{ post.date }}</p>
      <div v-html="post.excerpt.rendered"></div>
    </div>
    <!-- 空状态提示 -->
    <div v-if="filteredPosts.length === 0 && selectedMonth">该月份暂无文章</div>
    <!-- 加载状态提示 -->
    <div v-if="posts.length === 0">加载中...</div>
  </div>
</div>

2. Vue核心逻辑实现

以下是完整的Vue实例代码,包含WP数据获取、日期处理、筛选功能:

new Vue({
  el: '#app',
  data() {
    return {
      posts: [],          // 存储从WP API获取的原始文章数据
      filteredPosts: [],  // 存储筛选后的文章
      selectedMonth: '',  // 当前选中的月份
      uniqueMonths: []    // 所有可选的唯一月份列表
    }
  },
  mounted() {
    // 页面初始化时拉取WP文章数据
    this.fetchWPPosts();
  },
  methods: {
    async fetchWPPosts() {
      try {
        // 替换为你的WordPress站点API地址,per_page最大支持100,需分页请自行处理
        const res = await fetch('https://your-wp-site.com/wp-json/wp/v2/posts?per_page=100');
        this.posts = await res.json();
        
        // 处理文章日期,提取月份名称并生成唯一月份列表
        this.processPostDates();
        // 默认显示所有文章
        this.filteredPosts = [...this.posts];
      } catch (err) {
        console.error('文章加载失败:', err);
      }
    },
    processPostDates() {
      // 用Intl.DateTimeFormat统一生成月份名称(英文,需中文则改为'zh-CN')
      const dateFormatter = new Intl.DateTimeFormat('en-US', { month: 'long' });
      
      this.posts.forEach(post => {
        // 将WP返回的ISO日期转为Date对象,提取月份名称并挂载到post对象
        const postDate = new Date(post.date);
        post.monthName = dateFormatter.format(postDate);
      });
      
      // 提取唯一月份并排序,保证下拉选项有序不重复
      this.uniqueMonths = [...new Set(this.posts.map(p => p.monthName))].sort();
    },
    filterPostsByMonth() {
      if (!this.selectedMonth) {
        // 选中"所有月份"时重置为全部文章
        this.filteredPosts = [...this.posts];
        return;
      }
      // 根据选中月份过滤文章
      this.filteredPosts = this.posts.filter(post => post.monthName === this.selectedMonth);
    }
  }
});

3. 关键细节说明

  • WP API调用:WordPress默认开启REST API,若文章超过100篇,需要实现分页加载逻辑(循环请求page=1、page=2等)。
  • 日期处理:使用Intl.DateTimeFormat避免手动处理月份索引,自动生成规范的月份名称,支持多语言切换。
  • 性能优化:筛选操作基于本地原始数据,无需重复请求API,提升用户体验。
  • 边界处理:添加了加载状态、空状态提示,覆盖无数据、筛选无结果的场景。

4. 可选优化点

  • 添加CSS样式美化下拉框和文章列表。
  • 支持按年份+月份组合筛选(需修改日期处理逻辑,提取年份字段)。
  • 实现文章懒加载,当滚动到页面底部时自动加载下一页数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 21:53:11