列表排序(监视和计算属性)

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<!--
实现需求:模糊检索下列数据
1.收集用户的输入框的内容
2. 使用watch监视属性去监视keyWord的值(监视)
3.使用computed计算属性去实现

-->
<script src="./vue.js"></script>
</head>
<body>
<div id="root">
<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,index) in filpersons" :key='p.index'>
{{p.name}}--{{p.age}}
</li>
</ul>
<!-- <button @click="sortType = 2">升序</button>
<button @click="sortType = 1">降序</button>
<button @click="sortType = 0">原顺序</button> -->
</div>
<script type="text/javascript">
Vue.config.productionTip = false
new Vue({
el:'#root',
data:{
keyWord : '',
sortType: '', //0 原顺序,1降序,2升序
persons:[
{id:'001',name:'张1',age:'40'},
{id:'002',name:'李四',age:'20'},
{id:'003',name:'王五',age:'30'}
]
},
computed:{
filpersons(){
const arr = this.persons.filter((p)=>{
//问系统,persons名字是否和输入框的一样,不一样则为-1,一样则1
return p.name.indexOf(this.keyWord)!==-1;
})
if(this.sortType) {
//sort 排序规则
arr.sort((a,b)=>{
return this.sortType === 1 ? b.age-a.age:a.age-b.age

})
}
return arr
}
}

})
</script>
</body>
</html>

posted on 2022-12-05 21:23  爱前端的小魏  阅读(19)  评论(0编辑  收藏  举报

导航