1.列表过滤
<div id="test">
<input type="text" v-model="searchName">
<ul>
<li v-for="(p,index) in filterPersons" :key="index">
{{index}}----{{p.name}}----{{p.age}}
</li>
</ul>
</div>
<script type="text/javascript">
new Vue({
el:'#test',
data:{
searchName:'',
persons: [
{name: 'Tom', age:18},
{name: 'Jack', age:17},
{name: 'Bob', age:19},
{name: 'Mary', age:16}
],
},
//计算属性
computed:{
filterPersons(){
//定义所有相关的数据,取出
const {searchName,persons,orderType}=this
//过滤后最终需要显示的数组
let fPersons;
//对persons进行过滤
fPersons=persons.filter(p=>p.name.indexOf(searchName)!==-1)
return fPersons
});
</script>
2.列表的排序
<div id="test">
<ul>
<li v-for="(p,index) in filterPersons" :key="index">
{{index}}----{{p.name}}----{{p.age}}
</li>
</ul>
<button @click="setOrderType(1)">年龄升序</button>
<button @click="setOrderType(2)">年龄降序</button>
<button @click="setOrderType(0)">原本顺序</button>
</div>
<script type="text/javascript">
new Vue({
el:'#test',
data:{
searchName:'',
orderType:0,//0代表原本,1代表升序,2代表降序
persons: [
{name: 'Tom', age:18},
{name: 'Jack', age:17},
{name: 'Bob', age:19},
{name: 'Mary', age:16}
],
},
//计算属性
computed:{
filterPersons(){
//定义所有相关的数据,取出
const {searchName,persons,orderType}=this
//过滤后最终需要显示的数组
let fPersons;
//对persons进行过滤
fPersons=persons.filter(p=>p.name.indexOf(searchName)!==-1)
//排序
if(orderType!==0){
fPersons.sort(function (p1,p2) {//如果返回负数,p1在前;返回证树p2在前
if(orderType===2){
return p2.age-p1.age
}else{
return p1.age-p2.age
}
})
}
return fPersons
}
},
methods:{
setOrderType(orderType) {
this.orderType=orderType
}
}
});
</script>
全部代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>列表渲染_过滤与排序</title>
</head>
<body>
<!--
1.列表过滤
2.列表排序
-->
<div id="test">
<input type="text" v-model="searchName">
<ul>
<li v-for="(p,index) in filterPersons" :key="index">
{{index}}----{{p.name}}----{{p.age}}
</li>
</ul>
<button @click="setOrderType(1)">年龄升序</button>
<button @click="setOrderType(2)">年龄降序</button>
<button @click="setOrderType(0)">原本顺序</button>
</div>
<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript">
new Vue({
el:'#test',
data:{
searchName:'',
orderType:0,//0代表原本,1代表升序,2代表降序
persons: [
{name: 'Tom', age:18},
{name: 'Jack', age:17},
{name: 'Bob', age:19},
{name: 'Mary', age:16}
],
},
//计算属性
computed:{
filterPersons(){
//定义所有相关的数据,取出
const {searchName,persons,orderType}=this
//过滤后最终需要显示的数组
let fPersons;
//对persons进行过滤
fPersons=persons.filter(p=>p.name.indexOf(searchName)!==-1)
//排序
if(orderType!==0){
fPersons.sort(function (p1,p2) {//如果返回负数,p1在前;返回证树p2在前
if(orderType===2){
return p2.age-p1.age
}else{
return p1.age-p2.age
}
})
}
return fPersons
}
},
methods:{
setOrderType(orderType) {
this.orderType=orderType
}
}
});
</script>
</body>
</html>