17.品牌列表案例
<!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=adge"> <title>Document</title> <script src="vue.js"></script> </head> <body> <div id="app"> id:<input type="text" v-model="id"> name:<input type="text" v-model="name"> <input type="button" value="添加" @click="add"> <table border="1"> <tr> <th>序号</th> <th>名称</th> <th>时间</th> <th>操作</th> </tr> <tr v-for="item in pinpai" :key="item.id"> <td>{{item.id}}</td> <td>{{item.name}}</td> <td>{{item.date}}</td> <td> <a href="#" @click.prevent="del(item.id)">删除</a> </td> </tr> </table> </div> </body> <script> //创建Vue实例,得到ViewModel var vm=new Vue({ el:"#app", data:{ id:'', name:'', pinpai:[ {id:1,name:"奔驰",date:new Date()}, {id:2,name:"宝马",date:new Date()} ] }, methods:{ add(){ this.pinpai.push({id:this.id,name:this.name,date:new Date()}) this.id=this.name="" }, del(id){ //console.log(id) //分析业务逻辑: //1.根据拿到的商品id,查找到对应的商品索引 //2.根据拿到的索引值,去数组中调用splice方法删除对应的那个元素 /*for(let i=0;i<this.pinpai.length;i++){ if(this.pinpai[i].id==id){ this.pinpai.splice(i,1) break; } }*/ //另一种判断id,及删除方法 const index=this.pinpai.findIndex(function(item,i,arr){ //if(item.id==id){ //return true //} return item.id==id }) this.pinpai.splice(index,1) console.log(index) } } }); </script> </html>