1、综合应用vue的指令
①v-for 遍历的对象也可以是一个方法,v-for="(item,i) in search(keyword)"
②添加 v-for 遍历的元素同样可以添加 v-if 的判断,v-if 可以直接使用 v-for 遍历的结果进行判断操作,示例中我们筛选出了ID大于1的才渲染到界面上。
2、对象操作常用的方法
①遍历对象4中方法,some,findIndex,forEach,filter,
a、some 可以遍历对象可以终止,当匹配到需要的数据时可以 return true,函数体内可以执行其它代码
b、findIndex 同样可以终止遍历,当匹配到需要的数据时可以 return true,但是返回的是一个索引值
c、forEach 不能终止遍历,它会遍历完到最后
d、filter 是可以筛选出需要的数据,然后返回一个新的对象
②删除对象的方法,splice
删除索引开始的几个对象,例如示例中的 splice(i,1) 删除的是索引为i的对象,如果1改成2的话,那么将删除索引为 i 和 i+1 位置上的对象
③包含字符串判断方法,indexOf 和 includes
a、indexOf 它是获取包含字符串的位置,返回的是int类型的数字,如果传递的是空字符的话,它的值是0,字符串是包含空字符串的,console.log("我很棒!".indexOf(''))打印的结果就是0,所以示例代码中我们判断 indexOf(keyword) !=-1,-1是没有匹配上的判定
b、includes 是ES6新增的方法,它同样是判断字符串是否包含指定字符串的方法,includes返回是bool值,includes同样也包含空字符的,console.log("我很棒!".includes(''))打印的结果是true
示例代码如下:
<html>
<hred>
<meta charset="utf-8">
<meta name="viewport"
content="width=device-width,user-scalable=no,initial-scale=1.0, maximun-scale=1.0, minimun-scale=1.0">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/4.5.3/css/bootstrap.min.css">
<script src="https://cdn.bootcss.com/vue/2.5.2/vue.js"></script>
</hred>
<div id="app">
<div class="alert alert-primary">
<div>
<h3>三国群英会</h3>
</div>
<div class="form-inline">
<label>ID:<input class="form-control" type="text" v-model="id" /></label>
<label>名字:<input class="form-control" type="text" v-model="name" /></label>
<input type="button" class="btn btn-primary" value="添加" @click="add" />
<label>搜索名字:<input class="form-control" type="text" v-model="keyword" /></label>
</div>
</div>
<table class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th>ID</th>
<th>名字</th>
<th>时间</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(item,i) in search(keyword)" :key="item.ID" v-if="item.ID > 1">
<td>{{item.ID}}</td>
<td>索引:{{i}} -{{item.Name}}</td>
<td v-text="item.Date"></td>
<td><a href="#" @click.prevent="del(item.ID)">删除</a></td>
</tr>
</tbody>
</table>
</div>
<script type="text/javascript">
var vm = new Vue({
el: "#app",
data: {
id: "",
name: "",
keyword: "",
persons: [
{ ID: 1, Name: "刘备", Date: new Date() },
{ ID: 2, Name: "曹操", Date: new Date() },
{ ID: 3, Name: "孙权", Date: new Date() }
]
},
methods: {
add() {
this.persons.push({ ID: this.id, Name: this.name, Date: new Date() })
this.id = this.name = ""
},
del(id) {
// this.persons.some((item, i) => {
// if (item.ID == id) {
// this.persons.splice(i, 1)
// return true;
// }
// })
var index = this.persons.findIndex(item => {
if (item.ID == id) {
return true;
}
})
this.persons.splice(index, 1)
},
search(keyword) {
// var newPersons = []
// this.persons.forEach(item => {
// if(item.Name.indexOf(keyword) !=-1){
// newPersons.push(item);
// }
// });
// return newPersons
return this.persons.filter(item => {
if (item.Name.includes(keyword)) {
return item
}
})
}
}
})
</script>
</html>