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

如何使用v-for遍历嵌套对象并展示子分类内容?

解决Vue嵌套分类的v-for遍历问题

直接用嵌套v-for就能搞定,完全不用在同一元素里混写v-if和v-for,具体实现思路如下:

先明确数据结构(假设你的products是这种层级结构)

const products = [
  { name: 'Shorts', link: '/shorts' },
  { name: 'Socks', link: '/socks' },
  { 
    name: 'Shoes', 
    link: '/shoes',
    children: [
      { name: 'Shoes4men', link: '/shoes/men' },
      { name: 'Shoes4women', link: '/shoes/women' },
      { name: 'Shoes4kids', link: '/shoes/kids' }
    ]
  }
]

Vue模板实现代码

<template>
  <div class="product-list">
    <!-- 第一层v-for:遍历所有一级分类 -->
    <div v-for="(item, idx) in products" :key="idx" class="main-category">
      <!-- 渲染一级分类的文本和链接 -->
      <a :href="item.link">{{ item.name }}</a>

      <!-- 第二层v-for:只在有子分类时渲染 -->
      <div v-if="item.children" class="sub-category-group">
        <a 
          v-for="(subItem, subIdx) in item.children" 
          :key="subIdx" 
          :href="subItem.link"
          class="sub-category"
        >
          {{ subItem.name }}
        </a>
      </div>
    </div>
  </div>
</template>

核心逻辑说明

  1. 外层v-for负责渲染所有一级分类(Shorts、Socks、Shoes),每个分类作为独立容器
  2. 针对存在children属性的分类(比如Shoes),用内层v-for遍历其子项
  3. 这种写法完全符合Vue开发规范,规避了同一元素混用v-if和v-for的优先级问题(Vue官方明确不推荐这种混用,会导致逻辑混乱)

如果你的products是键值对形式的对象(而非数组),可以用v-for="(value, key) in products"遍历键值对,再判断value是否包含子结构即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 16:32:10