展示
(视频中有个删除不了的bug,代码已经改正,视频没录未更新)
讲解
根据条件筛选品牌
search
过滤方法中,使用 数组的 filter
方法进行过滤:
search(name) { return this.list.filter(x => { return x.name.indexOf(name) != -1; }); }
全部代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>品牌列表案例</title> <script src="./lib/vue-2.4.0.js"></script> <link rel="stylesheet" href="./lib/bootstrap-3.3.7.css"> </head> <body> <div id="app"> <div class="panel panel-primary"> <div class="panel-heading"> <h3 class="panel-title">添加品牌</h3> </div> <div class="panel-body form-inline"> <label> id: <input type="text" class="form-control" id="" v-model="id"> </label> <label> Name: <input type="text" class="form-control" v-model="name"> </label> <input type="button" value="添加" class="btn btn-primary" @click="add()"> <label> 搜索关键字: <input type="text" class="form-control" v-model="keywords"> </label> </div> </div> <table class="table table-bordered table-hover table-striped"> <thead> <tr> <th>id</th> <th>name</th> <th>ctime</th> <th>operation</th> </tr> </thead> <tbody> <tr v-for="item in search(keywords)" :key="item.id"> <td>{{ item.id }}</td> <td v-text="item.name"></td> <td>{{ item.ctime }}</td> <td> <a href="" @click.prevent="del(item.id)">删除</a> </td> </tr> </tbody> </table> </div> <script> // 创建vue 实例 得到viewmodel var vm = new Vue({ el:'#app', data:{ id:'', name:'', keywords:'', list: [ { id: 1, name: '奔驰', ctime: new Date() }, { id: 2, name: '宝马', ctime: new Date() } ] }, methods:{ // 添加信息的方法 add(){ // 1. 获取到 id 和 name ,直接从 data 上面获取 // 2. 组织出一个对象 // 3. 把这个对象,调用 数组的 相关方法,添加到 当前 data 上的 list 中 // 4. 注意:在Vue中,已经实现了数据的双向绑定,每当我们修改了 data 中的数据,Vue会默认监听到数据的改动,自动把最新的数据,应用到页面上; var car={id:this.id,name:this.name,ctime: new Date()}; this.list.push(car); this.id=this.name=''; }, // 根据Id删除数据 del(id){ /* this.list.some((item, i) => { if (item.id == id) { this.list.splice(i, 1) // 在 数组的 some 方法中,如果 return true,就会立即终止这个数组的后续循环 return true; } }) */ var index = this.list.findIndex(item=>{ if (item.id == id) { return true; } }); this.list.splice(index,1); }, // 根据关键字进行查找(因为是双向绑定,直接查找即可) search(keywords){ /* var newList = [] this.list.forEach(item => { if (item.name.indexOf(keywords) != -1) { newList.push(item) } }) return newList */ return this.list.filter(item=>{ // 注意 : ES6中,为字符串提供了一个新方法,叫做 String.prototype.includes('要包含的字符串') // 如果包含,则返回 true ,否则返回 false if (item.name.includes(keywords)) { return item; } }); } } }); </script> </body> </html>