<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<title>Title
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.js">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css">
<div id="app">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">添加品牌
<div class="panel-body form-inline">
Id:
<input type="text" class="form-control" v-model="id">
Name:
<input type="text" class="form-control" v-model="name">
<input type="button" value="添加" class="btn btn-primary" @click="add">
搜索:
<input type="text" class="form-control" v-model="keywords">
<table class="table table-bordered table-hover table-striped">
<th>Id
<th>name
<th>Ctime
<th>Operation
<tr v-for="item in search(keywords)" :key="item.id">
<td>{{item.id}}
<td>{{item.name}}
<td>{{item.ctime|dateFormat}}
<a href="" @click.prevent="remove(item.id)">删除
//过滤器的定义语法
//Vue.filter('过滤器名称',function(){})
//过滤器中的function,第一个参数,已经被规定死了,永远都是过滤器管道符前面传递过来的数据
Vue.filter('dateFormat', function(dataStr){
var time =new Date(dataStr);
function timeAdd0(str) {
if (str <10) {
str ='0' + str;
}
return str
}
var y = time.getFullYear();
var m = time.getMonth() +1;
var d = time.getDate();
var h = time.getHours();
var mm = time.getMinutes();
var s = time.getSeconds();
return y +'-' +timeAdd0(m) +'-' +timeAdd0(d) +' ' +timeAdd0(h) +':' +timeAdd0(mm) +':' +timeAdd0(s);
})
let vm=new Vue({
el:'#app',
data: {
id:'',
name:'',
keywords:'',
list:[
{id:1,name:'奔驰',ctime:new Date()},
{id:2,name:'宝马',ctime:new Date()}
]
},
methods:{
add(){
this.list.push({
id:this.id,
name:this.name,
ctime:new Date()
});
this.id=this.name='';
},
remove(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;
// }
// })
let 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=>{
//注意:ES6中,为字符串提供了一个新方法,叫做String.prototype.includes('要包含的字符串'),如果包含返回true,反之返回false;
if(item.name.includes(keywords)){
return item;
}
})
}
}
})
</html>