<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>列表排序</title>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
</head>
<body>
<div id="root">
<h2>人员列表</h2>
<input type="text" :placeholder="message" v-model="keyword">
<button @click="sorttype = 2">年龄升序</button>
<button @click="sorttype = 1">年龄降序</button>
<button @click="sorttype = 0">原顺序</button>
<ul>
<li v-for="p in persons2" :key="p.id">
{{p.name}}-{{p.age}}-{{p.sex}}
</li>
</ul>
</div>
<script type="text/javascript">
Vue.config.productionTip=false;
new Vue({
el:"#root",
data:{
message:'请输入名字搜索',
keyword:'',
persons:[
{id:'1',name:'马冬梅',age:30,sex:'女'},
{id:'2',name:'周冬雨',age:35,sex:'女'},
{id:'3',name:'周杰伦',age:18,sex:'男'},
{id:'4',name:'文兆伦',age:19,sex:'男'},
],
sorttype:0,
},
computed:{
persons2(){
const arr = this.persons.filter((p)=>{
return p.name.includes(this.keyword);
});
if (this.sorttype===0) {
return arr
}else if(this.sorttype===1){
return arr.sort((a,b)=>{
return b.age-a.age;
})
}else {
return arr.sort((a,b)=>{
return a.age-b.age;
})
}
console.log(arr);
}
}
})
</script>
</body>
</html>