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

使用Vue实现WordPress最新文章展示并排除当前文章的方案咨询

实现方案

你只需要新增一个过滤逻辑的计算属性即可,步骤如下:

  • 首先利用组件已经接收的slug prop(当前访问文章的别名)作为过滤标识
  • 过滤掉所有和当前文章slug匹配的内容
  • 对过滤后的文章列表取前3条,即可自动补位保证始终展示3篇最新的非当前访问文章

修改后完整代码:

<template>
    <section>
        <h4>Recent Posts</h4>
        <div class="posts-recent">
            <!-- 替换为过滤后的计算属性 -->
            <div v-for="(post, index) in filteredRecentPosts" :key="post.id" class="post">
                <div>
                    <nuxt-link :to="`/blog/${post.slug}`" class="post-image" :style="{ backgroundImage: 'url(' + post.fimg_url + ')' }"></nuxt-link>
                    <div class="post-text">
                    <nuxt-link :to="`/blog/${post.slug}`" class="post-title" v-html="post.title.rendered"></nuxt-link>
                    </div>
                </div>
              </div>
        </div>
    </section>
</template>

<script>
  import { mapState, mapActions } from 'vuex';
  
  export default {
    name: 'Recent',
    created() {
      this.getPosts();
    },
    props: {
      slug: String
    },
    computed: {
      ...mapState(['posts']),
      // 新增过滤逻辑的计算属性
      filteredRecentPosts() {
        return this.posts
          .filter(post => post.slug !== this.slug)
          .slice(0, 3)
      }
    },
    methods: {
      ...mapActions(['getPosts']),      
    }
  };
</script>

注意说明

  • 前提是你存在vuex中的posts数组已经按发布时间倒序排序(最新文章在前),这也是WordPress REST接口的默认返回排序规则,无需额外调整
  • 原代码中内层div的冗余key="index"已删除,避免Vue抛出重复key的警告

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 10:27:00