key
-
作用
给Vdom打上标记,实现同层次比较
-
案列:
<!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> </head> <body> <div id="app"> <ul> <li v-for = "(item,index) in todos" :key = "item.id" > <p> {{ item.task }} </p> <div class="btn_box"> <button @click = "modify"> 修改 </button> <button @click = "remove( index )"> 删除 </button> </div> </li> </ul> </div> </body> <script src="../../lib/vue.js"></script> <script> new Vue({ el: '#app', data: { msg: 'hello ', todos: [ { id: 1, task: '任务一' }, { id: 2, task: '任务二' } ] }, methods: { remove ( index ) { this.todos.splice( index,1 ) }, modify ( e ) { // 点击修改让整个li的背景颜色为红色 // 以下代码我是用来说明key的作用的,你在真实项目中不允许使用, 因为接下来我要操作dom了 const li = e.target.parentNode.parentNode li.style.background = 'red' } } }) </script> </html>
-
经验
列表渲染都要加key,key一定是要唯一的标识,最好是id
-