1. 列表过滤
运用了Vue实例化的 computed (计算属性)
例子:
<div id="test">
<input type="text" v-model='searchName'>
<ul>
<li v-for= "(p,index) in filterP":key="index">
{{index}}--{{p.name}}--{{p.age}}
</li>
</ul>
<button>年龄升序</button>
<button>年龄降序</button>
<button>原本顺序</button>
</div>
<script src="./vue.js"></script>
<script>
new Vue({
el : '#test',
data :{
searchName:"",
persons:[
{name : 'tom',age:18},
{name : 'tzh',age:19},
{name : 'txm',age:20}
]
},
computed: { //计算属性
filterP(){
const {persons,searchName} = this // 结构赋值
// 判断列表是否包含输入框的值
return persons.filter(p=>p.name.indexOf(searchName)!=-1)
}
},
})
没有输入值前:
输入值后:
2. 列表排序
例子:
<div id="test">
<input type="text" v-model='searchName'>
<ul>
<li v-for= "(p,index) in filterP":key="index">
{{index}}--{{p.name}}--{{p.age}}
</li>
</ul>
<button @click='change(1)'>年龄升序</button>
<button @click='change(2)'>年龄降序</button>
<button @click='change(0)'>原本顺序</button>
</div>
<script src="./vue.js"></script>
<script>
new Vue({
el : '#test',
data :{
searchName:"",
orderType : 0,//初始化判断条件
persons:[
{name : 'tom',age:20},
{name : 'tzh',age:19},
{name : 'txm',age:25},
{name : 'tzo',age:100},
]
},
computed: {
filterP(){
const {persons,searchName,orderType} = this
let newPersons;
newPersons = persons.filter(p=>p.name.indexOf(searchName)!=-1)
if(orderType != 0){
newPersons.sort((a,b)=>{
if(orderType == 1){
return a.age - b.age
}else{
return b.age - a.age
}
})
}
return newPersons
}
},
methods: {
change(msg){
this.orderType = msg
}
},
})
</script>
根据 age 的属性值排序。三个点击按钮对应相关的排序
版权声明:本文为weixin_43051270原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。