分析javascript
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" v-model="id"> </label> <label> Name: <input type="text" class="form-control" v-model="name"> </label> <!-- 在Vue中,使用事件绑定机制,为元素指定处理函数的时候,若是加了小括号,就能够给函数传参了 --> <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> <!-- 以前, v-for 中的数据,都是直接从 data 上的list中直接渲染过来的 --> <!-- 如今, 咱们自定义了一个 search 方法,同时,把 全部的关键字,经过传参的形式,传递给了 search 方法 --> <!-- 在 search 方法内部,经过 执行 for 循环, 把全部符合 搜索关键字的数据,保存到 一个新数组中,返回 --> <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>
注:用了bootstraphtml
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() { var car = { id: this.id, name: this.name, ctime: new Date() } this.list.push(car) this.id = this.name = '' }, del(id) { // 根据Id删除数据 // 分析: // 1. 如何根据Id,找到要删除这一项的索引 // 2. 若是找到索引了,直接调用 数组的 splice 方法 /* 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; } }) // console.log(index) this.list.splice(index, 1) }, search(keywords) { // 根据关键字,进行数据的搜索 /* var newList = [] this.list.forEach(item => { if (item.name.indexOf(keywords) != -1) { newList.push(item) } }) return newList */ // 注意: forEach some filter findIndex 这些都属于数组的新方法, // 都会对数组中的每一项,进行遍历,执行相关的操做; return this.list.filter(item => { // if(item.name.indexOf(keywords) != -1) // 注意 : ES6中,为字符串提供了一个新方法,叫作 String.prototype.includes('要包含的字符串') // 若是包含,则返回 true ,不然返回 false // contain //console.log(keywords); if (item.name.includes(keywords)) { return item } }) } });