v-for列表排序

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="vue.min.js"></script>
</head>
<body>
<div id="app">
<input type="text" v-model="userName"/>
<ul>
<li v-for="(p,index) in filterPerson">
{{index}}----{{p.name}}---{{p.age}}
</li>
</ul>
<button @click="setOderType(1)">升序</button>
<button @click="setOderType(2)">降序</button>
<button @click="setOderType(0)">原序</button>
</div>


<script type="text/javascript">
const vm = new Vue({
el:"#app",
data:{
userName:'',
orderType:0,
persons:[
{name:"Tom",age:12},
{name:"li",age:22},
{name:"jack",age:32}
]

},
computed:{
filterPerson(){
// 取出相关数据
const {userName,persons,orderType}=this
// 最终需要显示的数组
let fpersons;
// 对persons进行过滤
fpersons=persons.filter(p=>p.name.indexOf(userName)!==-1)

// 排序
if(orderType!==0){
// 返回负数p1在前 返回正数p2在前
fpersons.sort(function(p1,p2){
// 1代表升序 2代表降序
if(orderType===2){
return p2.age-p1.age
}else{
return p1.age-p2.age
}
})
}
return fpersons
}
},

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

原文地址:https://www.cnblogs.com/weixin2623670713/p/13129881.html