<div id="app">
<label>
Id:
<input type="text" v-model="id" />
</label>
<label>
品牌:
<input type="text" v-model="name" />
</label>
<button type="button" @click="add">添加</button>
<br />
<label>
根据品牌名称搜索:
<input type="text" v-model="search" @keyup="searchName" />
</label>
<table cellpadding="0" cellspacing="0" border="1">
<thead>
<tr>
<th>ID</th>
<th>创建时间</th>
<th>汽车品牌</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(item, i) in searchName()" :key="item.id">
<td>{{item.id}}</td>
<td>{{item.addDate}}</td>
<td>{{item.name}}</td>
<td @click="del(i)">删除</td>
</tr>
</tbody>
</table>
</div>
var vm = new Vue({
el: '#app',
data: {
id: '',
name: '',
search: '',
cars: [
{id: 1, addDate: new Date(), name: '宝马'},
{id: 2, addDate: new Date(), name: '奔驰'}
]
},
methods: {
add(){
// console.log(this.cars);
var objCar = {id: this.id, addDate: new Date(), name: this.name};
this.cars.push(objCar);
this.id = this.name = '';
},
searchName(){
// var newCars = [];
// this.cars.forEach(item => {
// // if(item.name.indexOf(this.search) != -1){
// // newCars.push(item);
// // }
// if(item.name.includes(this.search)) newCars.push(item);
// // console.log(item.name.includes(this.search));
// });
// return newCars;
// 数组的filter方法,作用是循环指定的数组,并把满足回调函数中指定条件的项返回,得到新的数组
// var newCars = this.cars.filter(item => {
// return item.name.includes(this.search);
// });
// return newCars;
return this.cars.filter(item => item.name.includes(this.search));
},
del(i){
// this.cars.some((item, i) => {
// if(item.id == id){
// this.cars.splice(i,1);
// }
// })
this.cars.splice(i,1);
return this.cars;
}
}
})
数组的filter方法,作用是循环指定的数组,并把满足回调函数中指定条件的项返回,得到新的数组