极其简陋的vue数据分页demo

213 阅读1分钟

今日遇到了需求,需要在vue组件当中获取数据并且以分页的形式展示数据,想到之前练习的时候没有做过分页这个逻辑,于是便趁着写好了页面还在等接口这段时间自己思考一下相关的逻辑吧,研究了一下完成了相关的需求,主要的思路我都在写在了注释里,结合代码还是很简单的。

效果如图所示

html部分

    <div id="app">
        <ul>
            <li class="title">
                <span>姓名:</span>
                <span>年龄:</span>
            </li>
            <li v-for="(item,index) in renderList" :key="index">
                <span>{{item.name}}</span>
                <span>{{item.age}}</span>
            </li>
        </ul>
        <div class="pagenation">
            <span class="pre-page" @click="pre">上一页</span>
            <p><span>{{currentIndex}}</span><span>/</span><span>{{handleList.length}}</span></p>
            <span class="next-page" @click="next">下一页</span>
        </div>
    </div>

js部分

<script src="https://cdn.jsdelivr.net/npm/vue"></script>
    <script>
        var app = new Vue({
            el: '#app',
            data: {
                allPages: 0,
                currentIndex: 1,
                list: [{
                        name: '刘德华',
                        age: 1
                    }
                    <!--此处可以复制n个{}-->
                ]
            },
            methods: {
                // 下一页按钮的点击事件
                next: function () {
                    if (this.currentIndex > this.renderList.length) return
                    this.currentIndex++
                },
                // 上一页按钮的点击事件
                pre: function () {
                    if (this.currentIndex === 1) return
                    this.currentIndex--
                }
            },
            computed: {
                // 处理渲染的数据 这里每页只渲染8个 所以将总的数据每8个{}push进一个数组 这样所返回数组的length就是总页数了
                handleList: function () {
                    let smallArr = []
                    let bigArr = []
                    const { list } = this
                    list.forEach((item, inedx) => {
                        if (smallArr.length === 0) {
                            bigArr.push(smallArr)
                        }

                        smallArr.push(item)

                        if (smallArr.length === 8) {
                            smallArr = []
                        }
                    })
                    return bigArr
                },
                // 当前渲染的列表 根据当前的页数currentIndex来渲染 分好页的数据 (第一页的数据为handleList[currentIndex - 1])
                renderList: function () {
                    return this.handleList[this.currentIndex - 1]
                }
            },
            created: function () {
                console.log(this.handleList)
                console.log(this.renderList)
            }
        })
    </script>

样式部分就略过啦~~~

tips:如果有什么问题请各位大神尽管羞辱我o(////▽////)q 如果能够帮到你 也是我的不胜荣幸 Thanks for watching