(1)品牌案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="bootstrap-3.3.7.css">
<style>
</style>
</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 for="">
ID:
<input type="text" class="form-control" v-model="id">
</label>
<label for="">
Name:
<input type="text" class="form-control" v-model="name">
</label>
<input type="button" value="添加" class="btn btn-primary" @click="add()">
<label for="">
搜索关键字:
<input type="text" class="form-control" v-model="keywords">
<input type="button" value="搜索" class="btn btn-primary" @click="search()">
</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>{{item.name}}</td>
<td>{{item.ctime}}</td>
<td>
<a href="" @click.prevent="del(item.id)">删除</a>
</td>
</tr>
</tbody>
</table>
</div>
<script src="../vue-dev/vue-dev/dist/vue.min.js"></script>
<script>
var wm = 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)
},
del(id) { // 根据id删除数据
分析:
// 1. 如何根据id找到要删除的这项的索引
// 2. 如果找到索引了直接调用数组的splice方法
// this.list.some((item, i) => { //在数组的some方法中,如果return true;就会立即终止这个数组的后续循环
// if (item.id == id) {
// this.list.splice(i, 1);
// return true;
// }
// })
// 方法2
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;
}
}
})
</script>
</body>
</html>