其他分享
首页 > 其他分享> > vue10-6 列表过滤-增加升降排序

vue10-6 列表过滤-增加升降排序

作者:互联网

sort()方法:

  示例:let  arr = [6, 8, 2, 3, 1]

  完整使用时:sort((a, b)=>{ a-b })  升序  、  sort((a, b)=>{ b-a }) 降序

  说明:a, b为相邻的两个元素,a-b,是差值大于0时,b元素往前提,a元素后移后于下一个元素继续比较知道最后; b-a反之,大的元素前提,小的后移继续比较

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>列表过滤-computed版</title>
    <script type="text/javascript" src="../js/vue.js"></script>
</head>
<body>
    <div id="root">
        <h2>人员搜索:</h2>
        <input type="text" placeholder="请输入关键字" v-model="keyWord">
        <button @click="sortType = 0">原顺序</button>
        <button @click="sortType = 1">降序</button>
        <button @click="sortType = 2">升序</button>
        <br/><br/>
        <div v-for="item in filPersons">
            {{item.id}}--{{item.name}}--{{item.age}}
        </div>
    </div>
    <script type="text/javascript">
        Vue.config.productionTip = false

        new Vue({
            el: '#root',
            data() {
                return {
                    keyWord: '',
                    sortType: 0,    // 0 原顺序   1降序   2升序
                    persons:[
                        {id: '001', name: '马冬梅', age: 19, sex: '女'},
                        {id: '002', name: '周冬雨', age: 20, sex: '女'},
                        {id: '003', name: '周杰伦', age: 21, sex: '男'},
                        {id: '004', name: '温兆伦', age: 22, sex: '男'},
                    ],
                }
            },
            computed:{
                filPersons(){
                    // 1. 先取出过滤好的数据
                
                    const arr = this.persons.filter((p)=>{
                            return p.name.indexOf(this.keyWord) !== -1
                    });
                    // 2. 根据用户点击,给过滤好的数组排序
                    if (this.sortType){
                        arr.sort((p1, p2)=>{
                            return this.sortType === 1 ? p2.age-p1.age : p1.age-p2.age
                        })
                    }
                    return arr
                }
            }
        })
    </script>
</body>
</html>

 

标签:arr,return,name,vue10,age,sex,列表,排序,id
来源: https://www.cnblogs.com/leafchen/p/16481387.html