实现效果:
升序后
?
?降序后
?列表过滤
实现代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>列表排序</title>
<!-- 引入Vue -->
<script type="text/javascript" src="../js/vue.js"></script>
</head>
<body>
<!-- 准备好一个容器 -->
<div id="root">
<!-- 遍历数组 -->
<h2>中国少年先疯队列表</h2>
<input type="text" placeholder="请输入名字" v-model="keyword">
<button @click="sortType = 2">年龄升序</button>
<button @click="sortType = 1">年龄降序</button>
<button @click="sortType = 0">原顺序</button>
<ul>
<!-- <li v-for="p in fillPersons" :key="p.id"> -->
<li v-for="(p,index) of fillPersons" :key="p.id">
姓名:{{p.name}}--年龄:{{p.age}}
</li>
</ul>
</div>
</body>
<script type="text/javascript">
Vue.config.productionTip = false // 阻止 vue 在启动时生成生产提示
new Vue({
el:"#root",
data:{
keyword:'',
name:"才疏学浅的小缘同学",
sortType:0, //0原顺序,1降序,2升序
persons:[
{id:'001',name:'王国庆',age:'22'},
{id:'002',name:'杨文杰',age:'21'},
{id:'003',name:'文荣辉',age:'20'},
{id:'004',name:'张成',age:'19'},
{id:'005',name:'魏晓辉',age:'18'},
{id:'006',name:'章宇轩',age:'22'},
],
},
//监视属性实现
// watch:{
// keyword:{
// immediate:true,
// handler(val){
// this.fillPersons = this.persons.filter((p)=>{
// return p.name.indexOf(val) !== -1
// })
// }
// }
// }
//计算属性实现
computed:{
fillPersons(){
const arr = this.persons.filter((p)=>{
return p.name.indexOf(this.keyword) !== -1
})
//判断一下是否需要排序
if(this.sortType){
arr.sort((p1,p2)=>{
return this.sortType === 1 ? p2.age - p1.age : p1.age - p2.age
})
}
return arr
}
}
})
</script>
</html>
|