过滤和排序不分开,都得是在原先的基础上,也就是过滤的基础上进行操作
sortType:是否排序的检测值 @click="sortType=2" 检测是否排序
进行逻辑判断:在计算属性部分
computed:{
//修改sortType重新计算
fillPersons(){//有人读取fillPersons
const arr= this.persons.filter((a) => {//a是数组中的每隔元素
//indexOf寻找使用具有想让字符串的 返回索引值 没有返回值-1
return a.name.indexOf(this.name) !== -1 //书写你匹配的条件 没有为-1
})//将过滤后的结果进行排序判读
if(this.sortType){
arr.sort((a,b)=>{
return this.sortType ===2 ? a.age-b.age : b.age-a.age
})
}
return arr
}
}
<!-- 准备容器 -->
<div id='root'>
<ul>
<!-- 使用数据的唯一标识不出问题 -->
<input type="text" placeholder="请输入名字" v-model:value='name'>
<button @click="sortType=2">年龄升序</button>
<button @click="sortType=1">年龄降序</button>
<button @click="sortType=0">原顺序</button>
<li v-for="(p,index) in fillPersons" :key="p.id">
{{p.name}}-{{p.age}}
<input type="text">
</li>
</ul>
</div>
<script>
new Vue({
el: '#root',
data: {
name: "",
sortType:0,//0原顺序 1降序 2升许
persons: [
{ id: 001, name: '张三', age: 12 },
{ id: 002, name: '李四', age: 10 },
{ id: 003, name: '王三', age: 17 },
{ id: 004, name: '张四', age: 20 }
],
},
computed:{
//修改sortType重新计算
fillPersons(){//有人读取fillPersons
const arr= this.persons.filter((a) => {//a是数组中的每隔元素
//indexOf寻找使用具有想让字符串的 返回索引值 没有返回值-1
return a.name.indexOf(this.name) !== -1 //书写你匹配的条件 没有为-1
})//将过滤后的结果进行排序判读
if(this.sortType){
arr.sort((a,b)=>{
return this.sortType ===2 ? a.age-b.age : b.age-a.age
})
}
return arr
}
}
});
</script>