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

Nuxt(Vue)中如何按多层分类结构筛选文章?

如何在Nuxt Content中筛选多层分组的分类文章

你的场景是:用Nuxt搭建的站点中,文章的分类采用多层分组结构(比如food、cars、math、space四个大组,每组下有多个具体分类),但现有的Nuxt Content查询代码只支持一维数组格式的categories,无法适配嵌套的分组结构。

现有问题回顾

  • 分类文件示例(如food.yml):
food:
    - title: Tacos
      slug: tacos
      description: "A"
    - title: Burger
      slug: burger
      description: "B"
    - title: Chicken
      slug: chicken
      description: "C"
    - title: Pizza
      slug: pizza
      description: "D"
    - title: Artichokes
      slug: artichokes
      description: "E"
    - title: Cereal
      slug: cereal
      description: "F"
  • 文章元数据的分类格式:
---
id: 999
title: 'YADA YADA YADA'
slug: yada-yada-yada
date: 'August 2nd, 2022'
img: Picture.png
categories:
    food:
        - Pizza
        - Chicken
        - Artichokes
---
  • 当前无效的查询代码(仅支持一维数组categories):
const posts2 = await this.$content('posts')
.where({ categories: { $contains: this.category } })
.sortBy('id', 'desc')
.fetch()
.catch();

解决方案

根据你是否知道目标分类所属的分组,有两种实现方式:

1. 已知分类所属分组时的精确查询

如果明确要筛选的分类属于某个大组(比如要找Pizza,知道它在food组下),可以直接通过嵌套属性路径来查询:

const posts2 = await this.$content('posts')
  // 用点语法指定嵌套的分类组路径
  .where({ 'categories.food': { $contains: this.category } })
  .sortBy('id', 'desc')
  .fetch()
  .catch(err => console.error(err));

2. 未知分类所属分组时的全局查询

如果不确定目标分类在哪个大组里,需要遍历所有分类组进行查询,可以用$or操作符结合动态生成的查询条件:

// 1. 先定义所有分类组的名称(也可以从文件系统动态读取)
const categoryGroups = ['food', 'cars', 'math', 'space'];

// 2. 生成每个分组的查询条件
const filterConditions = categoryGroups.map(group => ({
  [`categories.${group}`]: { $contains: this.category }
}));

// 3. 用$or组合所有条件,只要任意一个分组包含目标分类就匹配
const posts2 = await this.$content('posts')
  .where({ $or: filterConditions })
  .sortBy('id', 'desc')
  .fetch()
  .catch(err => console.error(err));

可选:动态读取分类组名称

如果不想硬编码分类组名称,可以从存放分类文件的目录动态读取:

// 在asyncData或server端代码中执行(需要Node.js的fs模块)
const fs = require('fs');
const path = require('path');

// 假设分类文件存放在项目根目录的content/categories下
const categoryDir = path.resolve(__dirname, 'content/categories');
const categoryGroups = fs.readdirSync(categoryDir)
  .filter(file => file.endsWith('.yml'))
  .map(file => file.replace('.yml', ''));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 15:15:30