我从API获得以下ajax响应:
{
"data": [
{
"id": 16,
"sender_id": 1,
"text": "Test",
"created_at": "2017-07-21 15:42:08",
"updated_at": "2017-07-21 15:42:08",
"sender": {
"data": {
"id": 1,
"name": "John Doe",
"email": "john@doe.co",
"mobile": "+1875446799976",
"photo_url": "https://example.co/storage/profiles/0H6Rkwsrlns0R1PY03Mta2qIhdPhV7N19jaagH3m.jpeg",
"first_login": 0,
"uses_two_factor_auth": false,
"two_factor_reset_code": null,
"current_team_id": 1,
"stripe_id": null,
"current_billing_plan": null,
"billing_state": null,
"vat_id": null,
"trial_ends_at": "2017-06-27 10:06:05",
"last_read_announcements_at": "2017-06-27 10:06:05",
"created_at": "2017-06-27 10:06:05",
"updated_at": "2017-06-28 10:40:07",
"tax_rate": 0
}
},
"buildings": {
"data": [
{
"id": 4,
"team_id": 1,
"name": "Oasis",
"created_at": "2017-06-30 13:15:30",
"updated_at": "2017-06-30 13:15:30",
"pivot": {
"sending_id": 16,
"building_id": 4
}
}
]
},
"messages": {
"data": [
{
"id": 316,
"sending_id": 16,
"recipient_id": 42,
"provider_id": "0B0000006A1ABFEF",
"info": null,
"status": "delivered",
"price": "0.07500000",
"error_text": null,
"created_at": "2017-07-21 15:42:08",
"updated_at": "2017-07-21 15:42:21",
"recipient": {
"id": 42,
"name": "John Doe",
"email": "john@doe.co",
"mobile": "198765456789",
"types": [
"Inhabitant"
],
"building_id": 4,
"created_at": "2017-07-01 07:21:52",
"updated_at": "2017-07-01 07:21:52",
"deleted_at": null
}
}
]
}
},
...
}
但是,当我尝试显示收件人名称时,如下所示:
<tr v-for="sending in sendings">
<td>{{ sending.created_at | moment }}</td>
<td><div style="width: 300px">{{ sending.text }}</div></td>
<td>
<div v-for="building in sending.buildings.data" v-if="sending.buildings.data">
{{ building.name }}
</div>
</td>
<td>
<ul>
<li v-for="message in sending.messages.data" v-if="sending.messages.data">
{{ message.recipient.name }}
</li>
</ul>
</td>
</tr>
我在控制台中收到此错误,根本没有显示任何行: TypeError:无法读取未定义的属性“name”
以下是API调用&amp;回调:
getSendings() {
axios.get('/api/v1/sendings', {
params: {
search: (this.searchSendings ? this.searchSendings.text : ''),
limit: this.sendings ? (this.sendings.length + 10) : 10,
building_id: this.selectedBuildingsIds
}
})
.then(response => {
if (response.data.data.length) {
this.sendings = response.data.data;
if (response.data.meta.pagination.total_pages == 1) {
this.$refs.infiniteLoading.$emit('$InfiniteLoading:complete');
} else {
this.$refs.infiniteLoading.$emit('$InfiniteLoading:loaded');
}
} else {
this.$refs.infiniteLoading.$emit('$InfiniteLoading:complete');
}
});
},
这是数据:
data() {
return {
sendings: null,
selectedBuildings: null,
selectedBuildingsIds: [],
searchSendings: {
text: null
},
};
},
这很奇怪,因为显示建筑名称的工作正常,唯一的区别是收件人更深一层......
有什么想法吗?
答案 0 :(得分:0)
我期望导致错误的是某个人message
,message.recipient
未定义。在未定义recipient
的情况下,当您尝试访问收件人的name
属性时,
{{message.recipient.name}}
Javascript会抛出错误,因为您现在正在尝试获取未定义的名称属性。
您可以使用警卫来保护自己免受该错误。
{{message.recipient && message.recipient.name}}