开发者问题收集

Vue 使用 v-for 时无法读取 null 属性

2020-04-29
996

有没有办法解决 v-bind:key="persons.id" 上未定义 id 的错误?

我的视图

<div v-for="reservation in reservationNameByTime" v-bind:key="reservation.id">
  {{reservation.id}} /** displays 1 **/
  <div v-for="player in reservation.Players" v-bind:key="player.id">
    {{player.id}} /**displays 1 **/
    <div v-for="persons in player.Person" v-bind:key="persons.id"> /** throws an error as id of null **/
      {{persons.name}}
    </div>
  </div>
</div>

JSON 数据

reservationNameByTime: [
 {
  id: 1,  /** defines reservation id **/
  Players: [
    id: 1,  /** defines players id **/
    Person:{
      id: 1,  /** defines the person id **/
      name: John
    }
   ]
 }
]

数组数据的图像

JSON 数组数据

3个回答
<div v-for="(reservation, i) in reservationNameByTime" v-bind:key="i">
    {{reservation.id}} /** displays 1 **/
    <div v-for="(player, j) in reservation.Players" v-bind:key="j">
        {{player.id}} /**displays 1 **/
        <div v-for="(persons, k) in player.Person" v-bind:key="k">
            {{persons.name}}
        </div>
    </div>
</div>
Willing Master
2020-04-29

您的数据格式不正确,请尝试使用您帖子中的 html 代码

reservationNameByTime: [{
    id: 1,
    Players: [{
        id: 1,
        Person: [{
            id: 1,
            name: 'John'
        },
        {
            id: 2,
            name: 'Marc'
        }]
    }]
}]

但是这个(下面)更好,对于每个预订,您都有一个 id 和一个玩家列表,玩家有 id 和姓名

reservation: [{
    id: 1,
    players: [{
        id: 21,
        name: 'John'
    },
    {
        id: 55,
        name: 'Marc'
    }]
},
{
    id: 2,
    players: [{
        id: 34,
        name: 'Adrien'
    },
    {
        id: 12,
        name: 'Marion'
    }]
}]

HTML / VUE

<div v-for="reservation in reservations" v-bind:key="reservation.id">
    {{reservation.id}}
    <div v-for="player in reservation.players" v-bind:key="player.id">
        {{player}}
    </div>
</div>
Adrien Leloir
2020-04-29

player.Person 是一个对象, v-for 对象 会遍历对象的属性并返回其值。在本例中,它将是 1John 。因此,您尝试获取 1.idJohn.id

如果您只有一个人,您可以这样做:

div v-bind:key="player.Person.id">
   {{player.Person.name}}
</div>
D Malan
2020-04-29