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

Nuxt中如何遍历对象数组集合?附代码报错修复方法

报错根因

代码共有3处问题,直接触发属性未定义的报错:

  • v-for 遍历目标写为单数形式product,但fetch钩子中赋值的变量是复数products,模板渲染时找不到实例上的product属性
  • 未在组件data选项中提前初始化products,Nuxt无法将该属性注册为响应式属性,渲染阶段无法识别
  • 未正确处理axios返回值:axios请求默认返回完整响应对象,业务数据存放在data字段下,直接赋值会导致拿到的不是产品数组;同时错误给<li>标签绑定了不存在的img属性,无法正常渲染产品图片。
修复步骤
  • 在组件配置中添加data选项,提前初始化products为空数组,保证渲染初期属性可被识别
  • 修正v-for遍历目标,将v-for="(product, key) of product"改为遍历已声明的products数组
  • 处理axios返回结果,从响应对象中取出dummyjson接口实际返回的产品数组再赋值
  • 移除li标签上无效的img绑定,使用原生<img>标签渲染产品图片
修复后完整代码
<template>
  <div>
    <p v-if="$fetchState.pending">Fetching products...</p>
    <p v-else-if="$fetchState.error">An error occurred :(</p>
    <div v-else>
      <h1>Nuxt products</h1>
      <ul>
        <li
          v-for="product in products"
          :key="product.id"
        >
          <img :src="product.thumbnail" :alt="product.title" />
          <p>{{ product.description }}</p>
        </li>
      </ul>
      <button @click="$fetch">Refresh</button>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      products: []
    }
  },
  async fetch() {
    const response = await this.$axios("https://dummyjson.com/products");
    // 从响应中取出实际的产品列表数组
    this.products = response.data.products;
  },
};
</script>
Nuxt 遍历集合的正确规范
  • 所有模板中引用的响应式变量,必须提前在data(选项式API)或setup(组合式API)中初始化,禁止在fetch、created等生命周期钩子中直接给未声明的变量赋值
  • v-for语法遵循v-for="单个临时变量 in 目标集合"的格式,临时变量名和目标集合名不能重复,避免引用冲突
  • 遍历输出列表时必须绑定唯一的:key值,优先使用数据自带的唯一标识(如产品id),不要使用数组索引作为key,防止列表更新时出现渲染错位
  • 接口请求完成后先核对返回数据结构,取出实际需要的集合内容再赋值给响应式变量,不要直接把整个请求响应对象赋值给列表变量

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 22:18:42