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

Vuetify:如何通过嵌套v-for在食谱卡片中渲染嵌套食材数组?

解决Vuetify食谱卡片嵌套食材数组渲染问题

问题分析

你的代码里有几个关键错误导致嵌套的missedIngredients数组无法正确渲染:

  • 拼写错误:recpies.missedIngredients 应为 recipe.missedIngredients
  • v-for 位置错误:将循环放在<v-list>上会导致每个食材生成独立列表,重复显示副标题
  • recipes 初始值应为数组而非对象,因为接口返回的是食谱数组

修正后的代码

Template部分

<template>
  <v-container>
    <v-row v-for="recipe in recipes" :key="recipe.id" align-center>
      <v-col>
        <v-card class="mx-auto my-12" max-width="374">
          <v-img class="align-end text-white" cover :src="recipe.image"></v-img>
          <v-card-title>{{ recipe.title }}</v-card-title>
          <v-row>
            <v-col dense cols="12">
              <!-- 仅当存在缺失食材时显示列表 -->
              <v-list v-if="recipe.missedIngredients && recipe.missedIngredients.length">
                <v-list-subheader>
                  Missing Ingredients {{ recipe.missedIngredientCount }}
                </v-list-subheader>
                <!-- 遍历单个食谱的missedIngredients数组 -->
                <v-list-item v-for="item in recipe.missedIngredients" :key="item.id">
                  {{ item.name }}
                </v-list-item>
              </v-list>
              <!-- 无缺失食材时的提示 -->
              <v-alert v-else variant="outlined" color="info">
                No missing ingredients needed!
              </v-alert>
            </v-col>
          </v-row>
        </v-card>
      </v-col>
    </v-row>
  </v-container>
</template>

Script部分

<script>
export default {
  data() {
    return {
      // 初始化为空数组,匹配接口返回的数据类型
      recipes: []
    }
  },
  mounted() {
    fetch('http://localhost:3000/recipes')
      .then(res => res.json())
      .then(data => this.recipes = data)
      .catch(err => console.log(err.message))
  }
}
</script>

关键修改说明

  1. 修正拼写错误:把recpies改为recipe,确保正确访问当前循环的食谱对象
  2. 调整v-for位置:将循环从<v-list>移到<v-list-item>上,这样整个列表只有一个副标题,每个食材对应一个列表项
  3. 初始化recipes为数组:接口返回的是食谱数组,初始值设为空数组可以避免v-for遍历对象时的错误
  4. 添加空值判断:用v-if检查missedIngredients是否存在且有内容,避免未加载或无数据时的渲染错误,同时添加v-else提示无缺失食材的情况

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 21:58:10