Vue 列表排序

具体实现

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>列表排序</title>
    <script type="text/javascript" src="../js/vue.js"></script>
</head>
<body>

<div id="root">
    <input type="text" placeholder="请输入名字" v-model="keyWord">
    <button @click="sortType = 2">升序</button>
    <button @click="sortType = 1">降序</button>
    <button @click="sortType = 0">默认</button>
    <ul>
        <li v-for="(p,index) in filPersons" :key="p.id">
            {{p.name}} - {{p.sex}} - {{p.age}}
        </li>
    </ul>
</div>

</body>

<script type="text/javascript">
    new Vue({
        el: '#root',
        data: {
            persons: [
                {id: '001', name: '王大锤', sex: '女', age: 36},
                {id: '002', name: '王小李', sex: '男', age: 19},
                {id: '003', name: '李大刚', sex: '男', age: 21},
                {id: '004', name: '王小刚', sex: '女', age: 20},
            ],
            keyWord: '',
            sortType: 0
        },
        computed: {
            filPersons() {
                const arr = this.persons.filter((p) => {
                    return p.name.indexOf(this.keyWord) !== -1
                })
                if (this.sortType) {
                    arr.sort((p1, p2) => {
                        return this.sortType === 1 ? p2.age - p1.age : p1.age - p2.age
                    })
                }
                return arr
            }
        }
    })
</script>

</html>


代码分析

首先确定用户的点击事件:设置 sortType:0(0:默认、1:升序、2:降序)

sortType: 0

根据 sortType:0 的值决定 升序 或 降序

if (this.sortType) {
    arr.sort((p1, p2) => {
        return this.sortType === 1 ? p2.age - p1.age : p1.age - p2.age
    })
}


posted @ 2022-04-12 11:08  春暖花开鸟  阅读(469)  评论(0编辑  收藏  举报