在Vue.js中如何获取嵌套数组内的MentorProfile字段数据
解决方案
首先确认notification.MentorProfile字段的数据类型,分两种场景处理:
- 如果
MentorProfile是单个对象(绝大多数业务场景下一个通知对应唯一的导师资料),不需要嵌套v-for遍历,直接访问属性即可,你当前的嵌套循环属于冗余写法,优化后代码示例:
<div v-for="notification in notifications" :key="notification.id"> <q-item clickable v-ripple> <q-item-section> {{ notification.text }} from </q-item-section> <q-item-section avatar> <q-avatar rounded> <!-- 如果接口返回头像字段,替换为下方写法即可 --> <!-- <img :src="notification.MentorProfile.avatar" alt="导师头像"> --> <img src="../assets/mentor.jpg" alt="导师头像"> </q-avatar> </q-item-section> <span>{{ notification.MentorProfile.name }}</span> </q-item> <q-separator /> </div>
- 如果
MentorProfile确实是数组类型,你现有的遍历逻辑是正确的,拿不到数据可以做两步排查:- 检查字段拼写:Vue严格区分大小写,确认字段名是
MentorProfile而非mentorProfile,内部属性是name而非Name/username等其他命名 - 打印原始数据确认返回值:可以在渲染区域增加调试代码
<pre>{{ JSON.stringify(notification.MentorProfile, null, 2) }}</pre>,查看接口返回的完整结构确认对应字段是否有值
- 检查字段拼写:Vue严格区分大小写,确认字段名是
如果需要避免空数据导致的渲染报错,可以增加判空逻辑,优化后的遍历代码如下:
<div v-for="notification in notifications" :key="notification.id"> <!-- 判空后再遍历,避免MentorProfile为null/undefined时报错 --> <div v-for="profile in notification.MentorProfile || []" :key="profile.id"> <q-item clickable v-ripple> <q-item-section> {{ notification.text }} from </q-item-section> <q-item-section avatar> <q-avatar rounded> <!-- 头像兜底,没有返回头像字段时用本地默认图 --> <img :src="profile.avatar || '../assets/mentor.jpg'" alt="导师头像"> </q-avatar> </q-item-section> <span>{{ profile.name }}</span> </q-item> <q-separator /> </div> </div>
内容的提问来源于stack exchange,提问作者Hemmyhtec Creatives
相关产品推荐
相关产品推荐

