<!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=edge">
<title>Document</title>
<!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
crossorigin="anonymous">
<script src="./lib/vue.js"></script>
</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>
<!-- bootstrap中input添加.form-control类,表示为input元素添加表单控件;
可以为标签元素添加CSS定制样式。
-->
Id:<input type="text" class="form-control" v-model="id">
</label>
<label>
Name:<input type="text" class="form-control" v-model="name">
</label>
<label>
搜索name关键字:<input type="text" class="form-control" v-model="keywords">
</label>
<!-- @click="add"调用add函数不能传参数
@click="add()"调用add函数 可以进行传参 -->
<input type="button" value="添加" class="btn btn-primary" @click="add">
</div>
</div>
<table class="table table-striped table-bordered">
<thead>
<tr class="active">
<th>Id</th>
<th>Name</th>
<th>Ctime</th>
<th>Operation</th>
</tr>
</thead>
<tbody>
<!-- 思路是过滤list 将符合条件的数据放到一个新List里 然后再for循环遍历 -->
<tr v-for="item in search(keywords)" :key="item.id">
<td>{{item.id}}</td>
<!-- v-text 等同于上面的表达式 -->
<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>
var vm = new Vue({
el: '#app',
data: {
id: '',
name: '',
keywords: '',
list: [
{ id: 1, name: '奔驰', ctime: new Date() },
{ id: 2, name: '宝马', ctime: new Date() },
{ id: 3, 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查找出该条数据在数组中的位置 然后删除
//splice() 方法向/从数组中添加/删除项目,然后返回被删除的项目。
//some() 方法会依次执行数组的每个元素:
//如果有一个元素满足条件,则表达式返回true , 剩余的元素不会再执行检测。
//如果没有满足条件的元素,则返回false。
//方法1
// this.list.some((item,i) => {
// 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);
},
//方式1
// search(keywords){
// var newList = [];
// this.list.forEach(element => {
// //遍历的数据中 包含输入的关键字
// if(element.name.indexOf(keywords)!=-1){
// newList.push(element);
// }
// });
// return newList;
// },
//方式2
search(keywords) {
var newList = this.list.filter(element => {
if (element.name.includes(keywords)) {
return element;
}
});
return newList;
}
}
})
</script>
</body>
</html>