15621857753

VUE学习05:computed开发列表排序和筛选功能

来源:齐鲁建站 栏目:开发教程 阅读: 日期:2021-12-17

本文介绍了VUE学习05:computed开发列表排序和筛选功能,也就是列表过滤和列表排序的问题,这是开发中经常遇到的问题,记录于此。

先来看效果图:

VUE

能升,能降,能筛选

然后上代码:

DIV部分

<div id="main">
    <h2>人员列表</h2>
    <input type="text" placeholder="请输入名字" v-model="keyWord" />
    <br>
    <br>
    <button type="button" @click="sortType = 2">年龄升序</button>
    <button type="button" @click="sortType = 1">年龄降序</button>
    <button type="button" @click="sortType = 0">原顺序</button>
    <ul>     
        <li v-for="(p,index) in filPersons" :key="p.id"> //在数据未破坏(比如没有升降操作)的情况下p.id可以改用index
            {{p.name}}-{{p.age}}-{{p.sex}}
        </li>
    </ul>    
</div>

JS部分

<script>
    new Vue({
        el: '#main',
        data: {
            keyWord:'',
            sortType:0, //0原顺序 1降序 2升序
            persons:[
                {id:'001',name:'马冬梅',age:18,sex:'女'},
                {id:'002',name:'周杰伦',age:20,sex:'男'},
                {id:'003',name:'周冬雨',age:19,sex:'女'},
                {id:'004',name:'温兆伦',age:25,sex:'男'}
            ]
        },
        computed:{
            filPersons(){
                //筛选,并赋值给数组arr
                const arr = this.persons.filter((p)=>{
                    return p.name.indexOf(this.keyWord) !== -1
                })
                //判断一下是否需要排序
                if(this.sortType){
                    //sort() 对数组的项目进行排序
                    arr.sort((a,b)=>{
                        // ? : 三元运算符
                        return this.sortType === 1 ? b.age-a.age : a.age - b.age
                    })
                }
                
                //输出
                return arr
            }
        }
    })
</script>

TAG: VUE
展开