1.列表过滤
第一步:收集用户的输入
<input type="text" placehoder="请输入你的内容" v-model=“ 后面定义的元素”></input>
v-model:后面定义的元素改变会触发事件。
第二步:触发事件后再computed或watch中编写触发后的结果
watch:
watch:{
KeyWord:{
immediate: true,
handler(val){
this.filPerson = this.persons.filter((p) => {
return p.name.indexOf(val) !== -1
})
}
}
}
immediate:TRUE 可以让页面加载的的自动加载一次
handler(新值,旧值)
filperson是个空数组,用来接收persons通过过滤后的数组,上面遍历的数组也是这个数组
person是一个原数组,里面包含所以的元素
filter是筛选的工具,返回值时是筛选名字中存在的值
computed:
computed:{
filPerson(){
return this.persons.filter((p)=>{
return p.name.indexOf(this.KeyWord)!==-1
})
}
}
定义filperson直接用来接收返回值
filperson是个空数组,用来接收persons通过过滤后的数组,上面遍历的数组也是这个数组
person是一个原数组,里面包含所以的元素
filter是筛选的工具,返回值时是筛选名字中存在的值
总结:
很显然用computed更加方便,也便于理解
运行结果:
2.列表排序
列表排序是在列表过滤的基础上进行的
列表排序的重要知识点:
变量名.sort((a,b)=>{
return b-a //降序
return a-b //升序
})
第一步:在data中创建一个变量,来控制按钮的触发
第二步:在body中建立按钮,来控制事件的触发
第三步:在computer中写数组的返回值(在写返回值的时候,就已经将属性排好)
body中的代码:
<button @click="sortType=0">原顺序</button> <button @click="sortType=1">升序排列</button> <button @click="sortType=2">降序排列</button>
computer中的代码:
filPerson(){ const vrr=this.persons.filter((p)=>{ return p.name.indexOf(this.KeyWord)!==-1 }) if (this.sortType){ vrr.sort((a,b)=>{ return this.sortType==1 ?a.age-b.age:b.age-a.age }) } return vrr }
效果展示: