萌新Vue入门Day3——过滤、排序
列表渲染
检索
通过text框输入关键字进行检索
<div id="test">
<input type="text" v-model="searchname">
<ul>
<li v-for="(p,index) in newStudents" :key="index">
name:{{p.name}},age:{{p.age}}
</li>
</ul>
</div>
<script src="../js/vue.js"></script>
<script>
const vm = new Vue({
el:'#test',
data:{
searchname:'',
students:[
{name:'A',age:18},
{name:'B',age:18},
{name:'C',age:21}
]
},computed:{
newStudents(){
const {searchname,students} = this
//相当于定义临时数组
let newStu
//p.name.indexOf(searchname)!== -1检验是否为真,从而进行过滤
newStu = students.filter(p => p.name.indexOf(searchname)!== -1)
return newStu
}
}
})
</script>
排序
在原有基础上添加排序,当然也保留了原有的过滤
<button @click="setorderType(1)">年龄升序</button>
<button @click="setorderType(2)">年龄降序</button>
<button @click="setorderType(0)">恢复顺序</button>
methods:{
//给按钮个编号,进行区分排序
setorderType(orderType){
this.orderType = orderType
}
},
computed:{
newStudents(){
const {searchname,students,orderType} = this
let newStu
newStu = students.filter(p => p.name.indexOf(searchname)!== -1)
//添加判断,是否进行排序
if(orderType !== 0){
newStu.sort(function (p1,p2) {
if(orderType === 2)
return p2.age-p1.age
else
return p1.age-p2.age
})
}
if(orderType === 0)
newStu = students
return newStu
}
}