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

Vue3访问Spring Boot返回数组内嵌套对象属性出现未定义警告问题

解决方案

错误根因

  • v-for作用域错误:承载value、attribute变量的标签写在了v-for绑定标签的外部,变量仅在v-for内部作用域生效,外部访问直接触发未定义报错
  • 数据结构适配错误:接口返回的item.attribute是长度为1的数组,数组第一个元素才是存储Attribute0~Attribute3的键值对对象,直接遍历数组无法拿到对应属性
  • 基础配置缺失:data中users字段被注释未初始化,接口返回的最外层是对象而非数组,直接遍历会出现不符合预期的情况

修复后代码

<template>
  <div>
    <!-- 用用户唯一ID做遍历key,稳定性更高 -->
    <div v-for="user in users" :key="user.user_id || user.player_id">
      <h2>{{user.name}}</h2> 
      <div class ="row">
        <div v-for="(item,index) in user.items" :key="index">
          <div class="item">
            <p class="text">{{item.name}}</p>
            <p class="text">{{item.type}}</p>
            <p class="text">{{item.uniquetype}}</p> 
            <p class="text">{{item.attribute}}</p>
            <!-- 取attribute数组第一个元素遍历键值对,内容放在v-for内部,可选链避免空值报错 -->
            <p v-for="(value, attrKey) in item.attribute?.[0]" :key="attrKey">
              {{attrKey}} : {{value}}
            </p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
export default {
  name: 'UserDataShow',
  data:() => ({
    // 恢复users的初始化声明
    users: [],
    groupname: '',
    parameter: [],
    propGroupid: '',
    players: []
  }),
  mounted() {
    if (this.users.length == 0) {
      this.$axios.get("/toFetchFromSpringBootAdress/"+this.$route.params.id)
      .then((response) => {
        // 把返回的外层对象转成数组,适配v-for遍历逻辑
        this.users = Object.values(response.data)
      })
    }
  }
}
</script>

内容的提问来源于stack exchange,提问作者ASP.NOOB

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 12:54:04