(尚010)Vue列表的搜素和排序

 

 

 

 1.test010.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!--
1.列表过滤
2.列表排序
-->
<div id="test">
<input type="text" v-model="searchName">
<ul>
<!--filterPersons应该为persons过滤后产生的结果-->
<li v-for="(p,index) in filterPersons" :key="index">
{{index}}--{{p.name}}---{{p.age}}
</li>
</ul>

<!--需要怎样排序,需要给orderType设置值-->
<button @click="setOrderType(1)">年龄升序</button>
<button @click="setOrderType(2)">年龄降序</button>
<button @click="setOrderType(0)">原本顺序</button>
</div>
<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript">
new Vue({
el:'#test',
data:{
searchName:'',
orderType:0,//自己设计:0代表原本顺序,1代表升序排序,2代表降序排序
//数组
persons:[
{name:'赵云',age:'18'},
{name:'张飞',age:'16'},
{name:'关羽',age:'21'},
{name:'刘备',age:'2'}
],
},
computed:{
//搜索过滤
filterPersons(){
//取出相关数据,并进行结构赋值
const {searchName,persons,orderType}=this
//定义最终返回数组(最终需要显示的数组)
let fPersons;

//对persons进行过滤
//需要看p.name中是否包含searchName,调用这个方法p.name.indexOf(searchName):indexOf为看字符串searchName在当前字符串p.name的下标
//一旦不等于-1,说明包含了
fPersons=persons.filter(p=>p.name.indexOf(searchName)!==-1);
//排序
if(orderType!==0){
//排序调用sort()方法,还需要传比较函数
fPersons.sort(function(p1,p2){//如果返回的是负数,p1在前;返回正数p2在前
//1代表升序排序,2代表降序排序
if(orderType===2){
return p2.age-p1.age;
}else{
return p1.age-p2.age;
}
})
}
return fPersons;
}
},

methods:{
setOrderType(orderType){
this.orderType=orderType
}
}
})
</script>
</body>
</html>

posted @ 2019-12-10 16:29  Curedfisher  阅读(370)  评论(0编辑  收藏  举报