18.品牌列表案例之品牌名称检索功能
indexOf的应用
includes的应用
<!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">     品牌检索: <input type="text" v-model="keywords" @change="searchName"> <table border="1"> <tr> <th>序号</th> <th>名称</th> <th>时间</th> <th>操作</th> </tr> <tr v-for="item in searchName()" :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:'', keywords:'', pinpai:[ {id:1,name:"奔驰",date:new Date()}, {id:2,name:"宝马",date:new Date()}, {id:3,name:"奔奔",date:new Date()}, {id:4,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) }, searchName(){ console.log(this.keywords) let lists=[] //循环pinpai中的每一项,拿到这一项后判断名称中是否包含关键字,如果包含,则把这一项添加到lists中 for(let i=0;i<this.pinpai.length;i++){ //方法一: /* if(this.pinpai[i].name.indexOf(this.keywords)!=-1){ lists.push(this.pinpai[i]) }*/ //方法二: if(this.pinpai[i].name.includes(this.keywords)) lists.push(this.pinpai[i]) } return lists } } }); </script> </html>