vue v-for迴圈中key屬性的使用
阿新 • • 發佈:2021-11-14
<!DOCTYPE html> <html lang="en"> <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"> <title>Document</title> <script src="./lib/vue-2.4.0.js"></script> </head> <body> <div id="app"> <div> <label>Id:<input type="text" v-model="id"> </label> <label>Name: <input type="text" v-model="name"> </label> <input type="button" value="新增" @click="add"> </div> <!-- 注意: v-for 迴圈的時候,key 屬性只能使用 number獲取string --> <!-- 注意: key 在使用的時候,必須使用 v-bind 屬性繫結的形式,指定 key 的值 --> <!-- 在元件中,使用v-for迴圈的時候,或者在一些特殊情況中, 如果 v-for 有問題,必須 在使用 v-for 的同時,指定 唯一的 字串/數字 型別 :key 值 --> <p v-for="item in list" :key="item.id"> <input type="checkbox">{{item.id}} --- {{item.name}} </p> </div> <script> // 建立 Vue 例項,得到 ViewModel var vm = new Vue({ el: '#app', data: { id:'', name: '', list: [ { id: 1, name: '李斯' }, { id: 2, name: '嬴政' }, { id: 3, name: '趙高' }, { id: 4, name: '韓非' }, { id: 5, name: '荀子' } ] }, methods: { add() { // 新增方法 this.list.unshift({ id: this.id, name: this.name }) } } }); </script> </body> </html>
本文來自學習小花,作者:aixuexi666888,轉載請註明原文連結:https://www.cnblogs.com/aixuexi666888/p/15551121.html