溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

怎么在vue中使用v-for實(shí)現(xiàn)循環(huán)

發(fā)布時(shí)間:2021-03-20 16:58:34 來(lái)源:億速云 閱讀:296 作者:Leah 欄目:web開(kāi)發(fā)

本篇文章為大家展示了怎么在vue中使用v-for實(shí)現(xiàn)循環(huán),內(nèi)容簡(jiǎn)明扼要并且容易理解,絕對(duì)能使你眼前一亮,通過(guò)這篇文章的詳細(xì)介紹希望你能有所收獲。

代碼如下所示:

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <script src="https://cdn.jsdelivr.net/npm/vue"></script>
 <title>vue中使用v-for</title>
</head>
<body>
 <div id="app">
  <h4>循環(huán)列表</h4>
  <table>
   <thead>
    <tr>
     <th>序號(hào)</th>
     <th>書(shū)名</th>
     <th>作者</th>
    </tr>
   </thead>
   <tbody>
    <tr v-for="(book,index) in books" :key="book.title">
     <td>{{index+1}}</td>
     <td>{{book.title}}</td>
     <td>{{book.author}}</td>
    </tr>
   </tbody>
  </table>
</div>
 <div id="app2">
  <h4>循環(huán)對(duì)象</h4>
  <div v-for="(value,key) in person">
   {{key}}:{{value}}
  </div>
 </div>
 <script>
  new Vue({
   el: '#app',
   data: {
    books: [{
      title: '水滸傳',
      author: '施耐庵',
     },
     {
      title: '三國(guó)演義',
      author: '羅貫中',
     },
     {
      title: '西游記',
      author: '吳承恩',
     },
     {
      title: '紅樓夢(mèng)',
      author: '曹雪芹',
     },
    ]
   }
  })
 </script>
 <script>
  new Vue({
   el: '#app2',
   data: {
    person: {
     name: 'Xsan',
     age: 26,
    }
   }
  })
 </script>
</body>
</html>

 "(book,index) in books"是循環(huán)表達(dá)式,式中的“(book,index)”不可調(diào)換位置,對(duì)象,第二個(gè)才是索引,且索引是從0開(kāi)始的,所以在下面寫(xiě)序號(hào)時(shí),才會(huì)是“+1” 第一個(gè)永遠(yuǎn)為對(duì)象。

   循環(huán)狀態(tài)保持。默認(rèn)情況下,如果數(shù)組中的順序發(fā)生變化,或者個(gè)數(shù)發(fā)生變化導(dǎo)致重新渲染,那么vue會(huì)重新利用之前的元素,而不會(huì)重新排序,這樣在某些情況下可能是想要的,但是絕大部分情況可能不是我們想要的,這時(shí)候可以添加key屬性??梢灾荒軌蚴莕umber和str類(lèi)型,那么在循環(huán)時(shí)一般使用循環(huán)出來(lái)的對(duì)象的某個(gè)唯一值,不要使用index來(lái)做key,這樣雖然用了,但是沒(méi)有效果。在vue2.2.x以上,在自定義組件上使用v-for,key是必須要寫(xiě)的。

上述內(nèi)容就是怎么在vue中使用v-for實(shí)現(xiàn)循環(huán),你們學(xué)到知識(shí)或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識(shí)儲(chǔ)備,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI