VUE中演示v-for爲什麼要加key

<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <script src="https://cdn.bootcss.com/vue/2.6.8/vue.min.js"></script>

  <title>v-for</title>

</head>

<body>
    <div id="app">
        <div>
          <input type="text" v-model="name">
          <button @click="add">添加</button>
        </div>
        <ul>
          <li v-for="(item, index) in list">
            <input type="checkbox"> {{index}}-{{item.name}}
          </li>
        </ul>
    <script>
        // 創建 Vue 實例,得到 ViewModel
        var vm = new Vue({
          el: '#app',
          data: {
            name: '',
            newId: 3,
            list: [
              { id: 1, name: 'aa' },
              { id: 2, name: 'bb' },
              { id: 3, name: 'cc' }
            ]
          },
          methods: {
            add() {
             //注意這裏是unshift
              this.list.unshift({ id: ++this.newId, name: this.name })
              this.name = ''
            }
          }
        });
      </script>
      </div>
</body>

選中bb
在這裏插入圖片描述
輸入dd,點擊添加,選中的是aa
在這裏插入圖片描述

添加key

<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <script src="https://cdn.bootcss.com/vue/2.6.8/vue.min.js"></script>

  <title>v-for</title>

</head>

<body>
    <div id="app">
        <div>
          <input type="text" v-model="name">
          <button @click="add">添加</button>
        </div>
        <ul>
          <li v-for="(item, index) in list" :key="item.id">
            <input type="checkbox"> {{index}}-{{item.name}}
          </li>
        </ul>
    <script>
        // 創建 Vue 實例,得到 ViewModel
        var vm = new Vue({
          el: '#app',
          data: {
            name: '',
            newId: 3,
            list: [
              { id: 1, name: 'aa' },
              { id: 2, name: 'bb' },
              { id: 3, name: 'cc' }
            ]
          },
          methods: {
            add() {
             //注意這裏是unshift
              this.list.unshift({ id: ++this.newId, name: this.name })
              this.name = ''
            }
          }
        });
      </script>
      </div>
</body

輸入dd,點擊添加,選中的還是bb
在這裏插入圖片描述
可以簡單的這樣理解:加了key(一定要具有唯一性) id的checkbox跟內容進行了一個關聯。是我們想達到的效果
詳細原因參考如下鏈接:https://www.jianshu.com/p/4bd5e745ce95

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章