Vue封装分页组件

本文介绍了一个基于Vue的自定义分页组件,包括CSS样式文件和JS文件的详细代码。该组件可以根据当前页码和总页数动态显示分页导航,并提供上一页、下一页及具体页码点击的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文地址:http://www.cnblogs.com/jh007/p/6185599.html

css样式文件 pagination.css

复制代码
ul, li {
    margin: 0px;
    padding: 0px;
}

.page-bar {
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

.page-button-disabled {
    color:#ddd !important;
}

.page-bar li {
    list-style: none;
    display: inline-block;
}

.page-bar li:first-child > a {
    margin-left: 0px;
}

.page-bar a {
    border: 1px solid #ddd;
    text-decoration: none;
    position: relative;
    float: left;
    padding: 6px 12px;
    margin-left: -1px;
    line-height: 1.42857143;
    color: #337ab7;
    cursor: pointer;
}

.page-bar a:hover {
    background-color: #eee;
}

.page-bar .active a {
    color: #fff;
    cursor: default;
    background-color: #337ab7;
    border-color: #337ab7;
}

.page-bar i {
    font-style: normal;
    color: #d44950;
    margin: 0px 4px;
    font-size: 12px;
}
复制代码

js文件 pagination.js

复制代码
(function (vue) {
    // html模板信息
    var template = '<div class="page-bar"> \
                     <ul> \
                       <li><a class="{{ setButtonClass(0) }}" v-on:click="prvePage(cur)">上一页</a></li> \
                       <li v-for="index in indexs"  v-bind:class="{ active: cur == index }"> \
                          <a v-on:click="btnClick(index)">{{ index < 1 ? "..." : index }}</a> \
                       </li> \
                       <li><a class="{{ setButtonClass(1) }}" v-on:click="nextPage(cur)">下一页</a></li> \
                     </ul> \
                   </div>'

    var pagination = vue.extend({
        template: template,
        props: ['cur', 'all'],
        computed: {
            indexs: function () {
                var left = 1
                var right = this.all
                var ar = []
                if (this.all >= 11) {
                    if (this.cur > 5 && this.cur < this.all - 4) {
                        left = this.cur - 5
                        right = this.cur + 4
                    } else {
                        if (this.cur <= 5) {
                            left = 1
                            right = 10
                        } else {
                            right = this.all
                            left = this.all - 9
                        }
                    }
                }
                while (left <= right) {
                    ar.push(left)
                    left++
                }
                if (ar[0] > 1) {
                    ar[0] = 1;
                    ar[1] = -1;
                }
                if (ar[ar.length - 1] < this.all) {
                    ar[ar.length - 1] = this.all;
                    ar[ar.length - 2] = 0;
                }
                return ar
            }
        },
        methods: {
            // 页码点击事件
            btnClick: function (data) {
                if (data < 1) return;
                if (data != this.cur) {
                    this.cur = data
                    this.$dispatch('btn-click', data)
                }
            },
            // 下一页
            nextPage: function (data) {
                if (this.cur >= this.all) return;
                this.btnClick(this.cur + 1);
            },
            // 上一页
            prvePage: function (data) {
                if (this.cur <= 1) return;
                this.btnClick(this.cur - 1);
            },
            // 设置按钮禁用样式
            setButtonClass: function (isNextButton) {
                if (isNextButton) {
                    return this.cur >= this.all ? "page-button-disabled" : ""
                }
                else {
                    return this.cur <= 1 ? "page-button-disabled" : ""
                }
            }
        }
    })

    vue.Pagination = pagination

})(Vue)
复制代码

使用方法如下

复制代码
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <title></title>
    <script src="vue.js"></script>
    <link href="pagination.css" rel="stylesheet" />
    <script src="pagination.js"></script>
</head>
<body>
    <div id="app">
        <vue-pagination :cur.sync="cur" :all.sync="all" v-on:btn-click="listen"></vue-pagination>
        <p>{{msg}}</p>
    </div>
    <script type="text/javascript">
        var app = new Vue({
            el: '#app',
            data: {
                // 当前页码
                cur: 1,
                // 总页数
                all: 100,
                msg: ''
            },
            components: {
                // 引用组件
                'vue-pagination': Vue.Pagination
            },
            methods: {
                listen: function (data) {
                    // 翻页事件
                    this.msg = '当前页码:' + data
                }
            }
        })
    </script>
</body>
</html>
复制代码

测试效果

Demo下载:https://github.com/yangchunjian/pagedemo


### Vue3 分页组件封装与使用 #### 创建分页组件 为了创建一个可重用的分页组件,在 `src/components` 文件夹下建立一个新的文件名为 `MyPagination.vue` 的文件[^2]。此文件将包含分页逻辑以及模板结构。 ```html <template> <div class="pagination"> <!-- 上一页按钮 --> <button :disabled="currentPage === 1" @click="prevPage">上一页</button> <!-- 显示当前页码和其他可见页码链接 --> <span v-for="(page, index) in pages" :key="index" ><a href="#" @click.prevent="goTo(page)" :class="{ active: currentPage === page }">{{ page }}</a></span > <!-- 下一页按钮 --> <button :disabled="currentPage >= totalPages" @click="nextPage">下一页</button> </div> </template> <script setup> import { ref, computed, watchEffect } from 'vue'; // 定义属性并接收父级传递的数据 const props = defineProps({ totalItems: { type: Number, required: true, }, itemsPerPage: { type: Number, default: 10, }, }); // 计算总共有多少页 const totalPages = computed(() => Math.ceil(props.totalItems / props.itemsPerPage)); // 当前显示的是第几页,默认为首页 let currentPage = ref(1); // 页面变化事件触发时通知父组件更新数据列表 const emit = defineEmits(['update']); function goTo(pageNumber) { if (pageNumber !== currentPage.value && pageNumber > 0 && pageNumber <= totalPages.value) { currentPage.value = pageNumber; emit('update', { page: currentPage.value }); } } function prevPage() { if (currentPage.value > 1) { goTo(currentPage.value - 1); } } function nextPage() { if (currentPage.value < totalPages.value) { goTo(currentPage.value + 1); } } </script> <style scoped> .pagination a.active { font-weight: bold; } </style> ``` 上述代码定义了一个简单的分页控件,它接受两个参数:总的条目数 (`totalItems`) 和每页要显示的数量 (`itemsPerPage`)。通过计算得出总共需要多少页(`totalPages`),并通过监听用户的交互来改变当前所处的位置(`currentPage`),同时向外部发送更新信号以便于刷新视图中的实际内容。 #### 使用分页组件 要在其他地方使用这个自定义好的分页插件,只需要按照如下方式引入即可: ```html <!-- ParentComponent.vue --> <template> <div> <!-- 数据表格或其他形式的内容区域 --> <!-- 底部放置分页器 --> <my-pagination :total-items="data.length" :items-per-page="pageSize" @update="handleUpdate"></my-pagination> </div> </template> <script setup> import MyPagination from './components/MyPagination.vue'; import { reactive } from 'vue'; const data = reactive([]); // 假设这是从服务器获取到的数据集合 const pageSize = 10; // 每页最多显示数量 async function fetchData(pageNum) { try { const response = await fetch(`/api/data?page=${pageNum}&size=${pageSize}`); const result = await response.json(); Object.assign(data, result.data || []); } catch (error) { console.error(error.message); } } function handleUpdate({ page }) { fetchData(page); } </script> ``` 在这个例子中,当点击不同的页码或者上下翻动的时候会调用 `fetchData()` 函数重新请求对应页面的数据,并将其赋给 `data` 变量从而达到动态渲染的效果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值