Nuxt Content 获取文章列表时怎么按自定义字段排序?

极客泽铭 阅读 3

我用 Nuxt Content 写了个博客,想按 frontmatter 里的 publishDate 字段排序,但试了几次都不生效,是写法有问题吗?

我的代码大概是这样:

const { data: articles } = await useAsyncData('articles', () => {
  return queryContent('articles')
    .where({ _type: 'markdown' })
    .sort({ publishDate: -1 })
    .find()
})

publishDate 在 md 文件里是 YYYY-MM-DD 格式,但排序结果还是乱的,求指点!

我来解答 赞 8 收藏
二维码
手机扫码查看
1 条解答
シ广红
シ广红 Lv1
省事的话,你把 sort 里的 publishDate 改成字符串比较就行了。日期格式排序有问题通常是因为按数字比较了,改成这样:

const { data: articles } = await useAsyncData('articles', () => {
return queryContent('articles')
.where({ _type: 'markdown' })
.sort({ 'publishDate': (a, b) => a > b ? -1 : 1 })
.find()
})


这下应该能正常按日期倒序排了,别想太复杂。
点赞
2026-03-29 21:29