1. 程式人生 > 其它 >Vue列表過濾

Vue列表過濾

列表過濾:

<script>
    const vm = new Vue({
        data:{
            keyWord:"",
           persons:[
               {id:'1001',name:"張三",age:21},
               {id:'1002',name:"張飛",age:21},
               {id:'1003',name:"李四",age:21},
               {id:'1004',name:"王五",age:21}
           ],
            examplePerson:[]
        },
        watch:{
            keyWord: {
                immediate:true,
                handler(val) {
                    this.examplePerson = this.persons.filter((p)=>{
                        return p.name.indexOf(val) !== -1
                    })
                }
            }
        }
    })
    vm.$mount(".app");
</script>
<script>
    const vm = new Vue({
        data:{
            keyWord:"",
           persons:[
               {id:'1001',name:"張三",age:21},
               {id:'1002',name:"張飛",age:21},
               {id:'1003',name:"李四",age:21},
               {id:'1004',name:"王五",age:21}
           ],
        },
        computed:{
            examplePerson(){
                return this.persons.filter((p) => {
                    return p.name.indexOf(this.keyWord) !== -1
                })
            }
        }
    })
    vm.$mount(".app");
</script>

新增排序功能

<script>
    const vm = new Vue({
        data:{
            keyWord:"",
           persons:[
               {id:'1001',name:"張三",age:21},
               {id:'1002',name:"張飛",age:22},
               {id:'1003',name:"李四",age:23},
               {id:'1004',name:"王五",age:12}
           ],
        },
        computed:{
            examplePerson(){
                let array = this.persons.filter((p) => {
                    return p.name.indexOf(this.keyWord) !== -1
                });
                array.sort((p1,p2)=>{
                    return p1.age-p2.age //升序
                })
                return array;
            }
        }
    })
    vm.$mount(".app");
</script>