vue——24-vue案例:删除添加搜索案例
引入
<script src="../frame/vue.js"></script>
<link rel="stylesheet" href="../frame/bootstrap.css">
html
<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" @keyup.enter="add">
</label>
<!--在事件中如果加了小括号 就可以给方法传参了-->
<input type="button" value="添加" class="btn btn-primary" @click="add()">
<label>
搜索名称关键字:
<input type="text" class="form-control" v-model="keywords" v-focus>
</label>
</div>
</div>
<table class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>time</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 v-text="item.id"></td>
<td v-text="item.name"></td>
<td>{{item.time|time}}</td>
<td>
<a href="" @click.prevent="del(item.id)">删除</a>
</td>
</tr>
</tbody>
</table>
</div>
let vm = new Vue({
el: '#app',
data: {
list: [
{id: 1, name: 'lucy', time: new Date()},
{id: 2, name: 'tom', time: new Date()},
{id: 3, name: 'john', time: new Date()},
{id: 4, name: 'bob', time: new Date()}
],
id: '',
name: '',
keywords: ''
},
methods: {
add() {
//1、获取 id 和 name ,直接从 data 上获取
//2、组织一个对象
//3、把这个对象,调用 数组的 相关方法,添加到 当前data上的list中
//4、注意:在vue中已经实现了数据的双向绑定,每当我们修改了 data 中的数据,vue会默认监听到数据的改动,自动把最新数据,应用到页面上
//5.我们更多的是在进行vm中model数据的操作,同时,在操作model数据的时候,指定的业务逻辑操作
let car = {id: this.id, name: this.name, time: new Date};
this.list.push(car);
this.id = this.name = '';
},
del(id) {
//1、如何根据id,找到要删除这项的索引
//2、如果找到了索引了,直接调用 数组的splice 方法
/*
//some方法
this.list.some((item, i)=>{
if(item.id===id){
this.list.splice(i,1);
//在 数组的some 方法中,如果return true,就会立即终止这个数组的后续循环
return ture;
}
})
*/
//findIndex方法
let index = this.list.findIndex((item) => {
if (item.id === id) {
return true;
}
});
this.list.splice(index, 1);
},
search(keywords) {
//通过执行for循环,把所有符合关键字的数据,保存到一个新数据中并返回
/*
//forEach方法
let 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 => {
//在es6中,为字符串提供了一个新方法,叫做 String.prototype.includes('要包含的字符串')
//如果包含,则返回true,否则返回false
if (item.name.includes(keywords)) {
return item;
}
});
}
},
filters: {
time(data) {
let dt = new Date(data);
let y = dt.getFullYear();
let m = dt.getMonth();
let d = dt.getDate();
// return y + '-' + m + '-' + d;
//模板
return `${y}-${m}-${d}`;
}
},
directives: {
'focus': {
inserted: function (el) {
el.focus();
}
}
}
})