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

有没有办法解决显示 id not defined on v-bind:key="persons.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

    }

   ]

 }

]

数组数据的图像

http://img3.mukewang.com/62d96340000145a303940303.jpg

元芳怎么了
浏览 456回答 3
3回答

哔哔one

player.Person是一个对象,并且v-for在对象上迭代对象的属性并返回其值。在这种情况下,它将是1and John。所以你试图得到1.idand John.id。如果你只有一个人,你可以这样做:div v-bind:key="player.Person.id">&nbsp; &nbsp;{{player.Person.name}}</div>

HUWWW

您的数据格式不正确,请使用您帖子中的 html 代码尝试此操作reservationNameByTime: [{&nbsp; &nbsp; id: 1,&nbsp; &nbsp; Players: [{&nbsp; &nbsp; &nbsp; &nbsp; id: 1,&nbsp; &nbsp; &nbsp; &nbsp; Person: [{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; id: 1,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; name: 'John'&nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; id: 2,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; name: 'Marc'&nbsp; &nbsp; &nbsp; &nbsp; }]&nbsp; &nbsp; }]}]但是这个(下)更好,对于每个预订,你有一个 id 和一个玩家列表,玩家有 id 和 namereservation: [{&nbsp; &nbsp; id: 1,&nbsp; &nbsp; players: [{&nbsp; &nbsp; &nbsp; &nbsp; id: 21,&nbsp; &nbsp; &nbsp; &nbsp; name: 'John'&nbsp; &nbsp; },&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; id: 55,&nbsp; &nbsp; &nbsp; &nbsp; name: 'Marc'&nbsp; &nbsp; }]},{&nbsp; &nbsp; id: 2,&nbsp; &nbsp; players: [{&nbsp; &nbsp; &nbsp; &nbsp; id: 34,&nbsp; &nbsp; &nbsp; &nbsp; name: 'Adrien'&nbsp; &nbsp; },&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; id: 12,&nbsp; &nbsp; &nbsp; &nbsp; name: 'Marion'&nbsp; &nbsp; }]}]HTML/VUE<div v-for="reservation in reservations" v-bind:key="reservation.id">&nbsp; &nbsp; {{reservation.id}}&nbsp; &nbsp; <div v-for="player in reservation.players" v-bind:key="player.id">&nbsp; &nbsp; &nbsp; &nbsp; {{player}}&nbsp; &nbsp; </div></div>

潇湘沐

<div v-for="(reservation, i) in reservationNameByTime" v-bind:key="i">&nbsp; &nbsp; {{reservation.id}} /** displays 1 **/&nbsp; &nbsp; <div v-for="(player, j) in reservation.Players" v-bind:key="j">&nbsp; &nbsp; &nbsp; &nbsp; {{player.id}} /**displays 1 **/&nbsp; &nbsp; &nbsp; &nbsp; <div v-for="(persons, k) in player.Person" v-bind:key="k">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {{persons.name}}&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; </div></div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript