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

如何在Nuxt.js HackerNews项目中按时间降序排序帖子

解决Nuxt.js HackerNews帖子按时间降序排序问题

核心思路

在获取到所有帖子数据后,使用JavaScript的sort()方法,基于帖子的time字段(Unix时间戳)进行降序排序,确保最新的帖子排在最前面。排序逻辑放在父组件pages/index.vue中处理,无需修改components/StoryCard.vue。

具体代码修改

假设你在index.vue中通过asyncData获取数据,修改后的代码示例:

export default {
  async asyncData({ $axios }) {
    // 获取新帖子ID列表
    const storyIds = await $axios.$get('https://hacker-news.firebaseio.com/v0/newstories.json')
    // 批量获取帖子详情
    const stories = await Promise.all(
      storyIds.slice(0, 20).map(id => $axios.$get(`https://hacker-news.firebaseio.com/v0/item/${id}.json`))
    )
    // 按时间降序排序
    const sortedStories = stories.sort((a, b) => b.time - a.time)
    return { stories: sortedStories }
  }
}

如果使用fetch方法获取数据,修改示例:

export default {
  data() {
    return {
      stories: []
    }
  },
  async fetch() {
    const storyIds = await this.$axios.$get('https://hacker-news.firebaseio.com/v0/newstories.json')
    const stories = await Promise.all(
      storyIds.slice(0, 20).map(id => this.$axios.$get(`https://hacker-news.firebaseio.com/v0/item/${id}.json`))
    )
    // 排序后赋值给数据变量
    this.stories = stories.sort((a, b) => b.time - a.time)
  }
}

异常处理(可选)

如果存在帖子缺失time字段的情况,可以添加判断逻辑,避免排序出错:

const sortedStories = stories.sort((a, b) => {
  // 缺失time的帖子排到末尾
  if (!a.time) return 1
  if (!b.time) return -1
  return b.time - a.time
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 00:10:45