vue key得理解
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="../js/vue.js"></script> </head> <body> <div id="app"> <button @click="addPerson">追加一条数据</button> <div v-for="item,index in list" :key="index"> 姓名:{{item.name}}-年龄:{{item.age}} <input type="text"> </div> </div> </body> <script> let vm = new Vue({ el: '#app', data: { list: [ {name: '张三', id: '001', age: 26}, {name: '李四', id: '002', age: 27}, {name: '王五', id: '003', age: 28} ] }, methods: { addPerson() { this.list.unshift({ name: '老刘', id: '004', age: 29 }); } } }) </script> </html>
如上key是index效果如下
点击追加一条数据input里面得值不是一一对应得,因为vue会根据对应得key去进行匹配
把key换成唯一标识id就不会出现数据错乱得问题