增删查、过滤器
第1步:
npm init -y
生成 .json文件
第2步:
npm i bootstrap -S
生成2个文件
<link rel="stylesheet" href="./node_modules/bootstrap/dist/css/bootstrap-grid.min.css">
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.9/vue.js"></script>
<link
rel="stylesheet"
href="./node_modules/bootstrap/dist/css/bootstrap.min.css"
/>
</head>
<body>
<div id="app">
<div>
<label>Id:</label>
<input type="text" v-model="id" />
<label>Name:</label>
<input type="text" v-model="name" />
<input
type="button"
value="添加"
class="btn btn-primary"
@click="add"
/>
<label>按照品牌名称取检索::</label>
<input type="text" v-model="keyWords" @change="searchByName" />
</div>
<table class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Ctime</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(item,index) in searchByName()" :key="item.id">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.ctime}}</td>
<td>
<!-- 避免用一元操作符作为属性名delete -->
<!--传索引 -->
<a href="http://www.baidu.com" @click.prevent="del(index)"
>删除</a
>
<!-- 传id -->
<!-- <a href="http://www.baidu.com" @click.prevent="del(item.id)"
>删除</a
> -->
</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
<script>
const app = 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() },
{ id: 4, name: "奔奔", ctime: new Date() },
],
},
methods: {
// 添加
add() {
this.list.push({ id: this.id, name: this.name, ctime: new Date() });
this.id = this.name = "";
},
// 删除(根据索引)
del(index) {
// console.log(index);
this.list.splice(index, 1);
},
// 删除(根据id)
// del(id) {
// const index = this.list.findIndex((item) => {
// return item.id == id;
// });
// this.list.splice(index, 1);
// // findIndex 如果为true 返回数组下标
// },
// 查找
// 第1种
searchByName() {
let result = [];
// 循环list中的每一项,拿到这一项之后,判断名称中是否包含:关键字,如果包含,则把这一项添加到result 中
for (let i = 0; i < this.list.length; i++) {
if (this.list[i].name.indexOf(this.keyWords) != -1) {
result.push(this.list[i]);
}
}
return result;
},
// searchByName() {
// let result = [];
// // 循环list中的每一项,拿到这一项之后,判断名称中是否包含:关键字,如果包含,则把这一项添加到result 中
// for (let i = 0; i < this.list.length; i++) {
// // includes 有为true
// if (this.list[i].name.includes(this.keyWords)) {
// result.push(this.list[i]);
// }
// }
// return result;
// },
// 第2种(高阶函数)
// searchByName() {
// const newArr = this.list.filter((item) => {
// // return item.name.indexOf(this.keyWords) != -1;
// return item.name.includes(this.keyWords);
// });
// return newArr;
// },
// searchByName() {
// return this.list.filter((item) => {
// // return item.name.indexOf(this.keyWords) != -1;
// return item.name.includes(this.keyWords);
// });
// },
},
});
</script>
全局过滤器,处理时间
npm i moment -s