列表的搜索+排序
<!--
列表过滤+列表排序
-->
<div id="app">
<input type="text" v-model="searchName">
<ul>
<li v-for="(i,index) in filterPersons" :key="index">
{{index}}---{{i.name}}---{{i.age}}
</li>
</ul>
<button @click="orderType=1">年龄升序</button>
<button @click="setOrderType(2)">年龄降序</button>
<button @click="setOrderType(0)">原本顺序</button>
</div>
<script src="./js/vue.js"></script>
<script>
new Vue({
el:'#app',
data:{
searchName:'',
persons:[
{name:'tom',age:18},
{name:'jack',age:26},
{name:'ben',age:20},
{name:'malk',age:27},
],
orderType:0,//0原来顺序,1升序,2降序
},
computed: {
filterPersons(){
//取出相关的数据
const {searchName, persons,orderType} = this;
//最终需要显示的数组
let fPersons;
//对persons进行过滤
fPersons = persons.filter(b => b.name.indexOf(searchName)!==-1);
//找到返回下标,找不到返回-1,对象b可自行定义
if(orderType!==0){
fPersons.sort(function(p1,p2){
//1升序,2降序
if(orderType==1){//升序
return p1.age-p2.age;
}
else{//降序
return p2.age-p1.age;
}
})
}
return fPersons;
}
},
methods:{
setOrderType(type){
this.orderType=type
}
}
})
</script>