mvvm框架(VUE、React)中指定列表KEY的作用
直接上代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div id="app"> <div> <input type="text" v-model="uname"> <button @click.stop.prevent="add">添加</button> </div> <ul> <li v-for="(item, index) in list" :key="item.id"><input type="checkbox">{{item.id}}---{{item.name}}</li> </ul> </div> <script src="http://ybf-shopnew.oss-cn-beijing.aliyuncs.com/web_vendor/vendor/js/vue/vue.js?v=1"></script> <script> const vm = new Vue({ el: '#app', data: { uname: '', list: [ {id:0, name:'张三'}, {id:1, name:'李四'}, {id:2, name:'王五'} ] }, methods: { add(){ this.list.unshift({ id : this.list.length, name : this.uname }); } } }); </script> </body> </html>
原创文章请随便转载。愿和大家分享,并且一起进步。-- 江 coder