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

如何在VueJS中通过WordPress API根据分类ID获取分类名称

解决VueJS中WordPress API分类ID转名称的问题

嘿,我来帮你搞定把分类ID转成实际名称的问题!其实思路很简单:先从WordPress API获取所有分类的完整数据,建立ID到名称的映射,之后就能轻松把文章里的分类ID转换成对应的名称啦。

步骤1:修改数据结构,添加分类映射存储

首先在Vue的data里新增一个对象,用来存放分类ID和名称的键值对:

var app = new Vue ({
  el: "#wp-app",
  data: function() {
    return {
      searchQuery: '',
      categories: {}, // 新增:存储分类ID -> 名称的映射
      sources: [
        { name: 'TechCrunch', url: '//techcrunch.com/wp-json/wp/v2/posts?per_page=5&_embed', posts: [] }
      ]
    }
  },
  // 其他部分不变
});

步骤2:添加获取分类数据的方法

接下来新增一个方法,专门从WordPress API拉取所有分类信息,并填充到categories对象中:

methods: {
  // 新增:获取分类数据
  getCategories: function() {
    const self = this;
    // 请求分类列表,per_page设为100(WP API默认最大限制),覆盖大部分博客的分类数量
    this.$http.get('//techcrunch.com/wp-json/wp/v2/categories?per_page=100')
      .then(function(response) {
        // 遍历分类数据,构建ID到名称的映射
        response.data.forEach(category => {
          self.$set(self.categories, category.id, category.name);
        });
      }, function() {
        console.log('获取分类数据失败,请检查API链接');
      });
  },
  // 你原有的getPosts和generateUrl方法保持不变
  getPosts: function(){ /* ... */ },
  generateUrl: function(source) { /* ... */ }
},

步骤3:调整初始化逻辑,先拉分类再拉文章

在mounted钩子中,先调用getCategories获取分类映射,再拉取文章数据:

mounted: function(){
  this.$nextTick(function(){
    this.getCategories(); // 先获取分类映射
    this.getPosts();      // 再获取文章
  });
}

步骤4:在模板中显示分类名称

现在你就可以在模板里把文章的分类ID转换成名称了,比如遍历分类ID数组,用映射对象获取对应名称:

<!-- 假设你正在遍历文章列表 -->
<div v-for="post in source.posts" :key="post.id">
  <h2>{{ post.title.rendered }}</h2>
  <p class="post-categories">
    分类:
    <span v-for="(categoryId, index) in post.categories" :key="categoryId">
      {{ categories[categoryId] }}
      <!-- 添加逗号分隔,最后一个分类不加 -->
      <span v-if="index < post.categories.length - 1">, </span>
    </span>
  </p>
  <p class="post-date">{{ post.date | niceDate }}</p>
</div>

可选:添加过滤器简化模板代码

如果你觉得模板里直接写categories[categoryId]不够优雅,可以新增一个过滤器:

filters: {
  niceDate: function(value) {
    if(!value) return '';
    var date = moment.utc(value);
    return date.format('MMM DD, YYYY');
  },
  // 新增:根据ID获取分类名称
  getCategoryName: function(categoryId) {
    return this.categories[categoryId] || '未知分类';
  }
},

然后模板里就可以这样用:

<span>{{ categoryId | getCategoryName }}</span>

这样处理后,就能完美把文章里的分类ID转换成用户友好的分类名称啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 10:13:06