<template>
<div>
<input type="text" v-model="searchName" minlength="1" maxlength="10">
<ul>
<li v-for="(item,index) in filterList" :key="index">
{{item.name}}--{{item.age}}
</li>
</ul>
<button @click="setSortName(1)">年龄升序</button>
<button @click="setSortName(2)">年龄降序</button>
<button @click="setSortName(0)">原本顺序</button>
</div>
</template>
<script>
export default{
data(){
return{
list:[
{name:"张一",age:21},
{name:"高二",age:20},
{name:"张三",age:35},
{name:"高五",age:34}
],
searchName:"", //input框输入的值
sortName:0//0代表原本顺序 1代表升序 2代表降序
}
},
computed:{
filterList(){
// 取出相关的数据
const {searchName,list,sortName} = this
// 对list进行过滤
let nList;
nList = list.filter(item=>item.name.indexOf(searchName)!==-1)
//排序
if(sortName!==0){
nList.sort(function(left,right){
//如果返回负数let在前,正数right在前
if(sortName===2){
return right.age-left.age//降序
}else{
return left.age-right.age//升序
}
})
}
return nList
}
},
methods:{
setSortName(sortName){
this.sortName = sortName
}
}
}
</script>
|