<body>
<div id="div1">
<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">
</label>
<label>
<input type="button" value="添加" class="btn btn-primary" @click="add">
</label>
<label>
搜索名称关键字:
<input type="text" v-model="keywords" class="form-control">
</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">
<!-- 之前数据是从data上的list直接渲染过来的 -->
<!-- 现在定义一个search方法同时把关键字通过传参的形式传递给search方法 -->
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.ctime|dateFormat('')}}</td>
<td><a href="" @click.prevent="del(item.id)">删除</a></td>
</tr>
</tbody>
</table>
</div>
<script>
Vue.filter("dateFormat",function(dateStr,pattern){
var dt=new Date(dateStr)
var y=dt.getFullYear()
var m=dt.getMonth()+1
var d=dt.getDate()
if(pattern.toLowerCase()==='yyyy-mm-dd'){
return `${y}-${m}-${d}`}
else{
var hh=dt.getHours()
var mm=dt.getMinutes()
var ss=dt.getSeconds()
return `${y}-${m}-${d} ${hh}:${mm}:${ss}`
}
})
Vue.config.devtools = true;
var vm=new Vue({
el:'#div1',
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=''//添加完成后清空输入框
},
del(id){//删除列表
// this.list.some((item,i)=>{
// if(item.id==id){
// this.list.splice(i,1)
// return true;
// //在some方法中,如果热return true,就会立即终止这个数组循环
// }
// })
var index=this.list.findIndex(item=>{
if(item.id==id){
return true;}
})
this.list.splice(index,1)
},
search(keywords){//根据关键字进行数据搜索
return this.list.filter(item=>{
// if(item.name.indexOf(keywords) !=-1){
// newlist.push(item)
// }
if(item.name.includes(keywords))
//ES6中提供一个方法 string.prototype.includes('字符串')
//若包含则返回true,否则false
{return item}
})
// return newlist
}
}
})
</script>
</body>
列表案例.png
网友评论