Vue实现品牌列表案例
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>品牌列表案例</title>
<script src="https://cdn.staticfile.org/vue/2.6.10/vue.js"></script>
<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.3.1/css/bootstrap.min.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>
Id:
<input type="text" class="form-control" v-model="id">
</label>
<label>
Name:
<input type="text" class="form-control" v-model="name">
</label>
<input type="button" value="添加" class="btn btn-primary" @click="add">
<label>
搜索名称关键字:
<input type="text" class="form-control" v-model="keywords">
</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>
<!-- 之前v-for中的数据都是从data上的list中直接渲染过来的,现在定义了一个search方法,-->
<!-- 同时,把所有的关键字,通过传参的形式,传递给了search方法-->
<!-- 在search方法内部,通过执行for循环,把所有符合搜素关键字的数据,保存到一个新数组中返回-->
<tr v-for="item in search(keywords)" :key="item.id">
<td>{{item.id}}</td>
<td v-text="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 = 'yyyy-mm-dd hh:mm:ss') {
//根据给定的时间字符串,得到特定的时间
var dt = new Date(dateStr)
var y = dt.getFullYear()
var m = dt.getMonth() + 1
var d = dt.getDate()
// return y+'-'+m+'-'+d
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}`
}
})
var vm = new Vue({
el: '#app',
data: {
id: '',
name: '',
keywords: '',
list: [
{id: 1, name: '奔驰', ctime: new Date()},
{id: 2, name: '宝马', ctime: new Date()}
]
},
methods: {
add() {
// console.log('666')
var car = {id: this.id, name: this.name, ctime: new Date()}
this.list.push(car)
this.id = this.name = ''
},
del(id) {
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
// 注意:forEach some filter findIndex这些都属于数组的新方法,都会对数组中的每一项进行遍历,执行相关的操作
var newList = this.list.filter(item => {
// 注意:ES6中,为字符串提供了一个新方法,叫做String.prototype.includes('要包含的字符串'),如果包含返回true,否则返回false
if (item.name.includes(keywords)) {
return item
}
})
return newList
}
}
})
</script>
</body>
</html>