Vue封装 分页组件

在这里插入图片描述

思路:
1.父子组件通过 props 传递相关参数
2.子组件改变父组件的参数通过 $emit 方法来触发
代码:

<div class="Pagination">
        <div class="page-bar"> 
            <ul> 
                <li><a  v-on:click="goPage(cur-1)" :class="cur<=1 ? 'page-button-disabled':''">上一页</a></li>  
                <li v-for="index in indexs"  v-bind:class="{ active: cur == index }" :key="index"> 
                    <a v-on:click="goPage(index)">{{ index<1 ? "..." : index }}</a> 
                </li> 
                <li><a  v-on:click="goPage(cur+1)" :class="cur>=all ? 'page-button-disabled':''">下一页</a></li> 
            </ul> 
        </div>
    </div>
<script>
export default {
    name:'Pagination',
    props: ['cur','all'],
    computed: {
        indexs: function () {
            var left = 1;
            var right = this.all;
            var n = this.cur;
            var ar = []
            if (this.all >= 11) {
                if (n > 5 && n < this.all - 4) {
                    left = n - 5
                    right = n + 4
                } else {
                    if (n <= 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: {
        //上 、下一页
        goPage: function (index) {
            if (index > this.all) return;
            this.$emit('set-current-page', index);
            this.$emit('btn-click', index)
        },
    }
}
</script>
<style scoped>
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;pointer-events: none;}
.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: #42a032;cursor: pointer;}
.page-bar a:hover {background-color: #eee;}
.page-bar .active a {color: #fff;cursor: default;background-color: #1696a9;border-color: #1696a9;}
.page-bar i {font-style: normal;color: #d44950;margin: 0px 4px;font-size: 12px;}
</style>

在父组件引用:

<Pagination v-bind:cur="cur" v-bind:all="all" v-on:btn-click="listen" v-on:set-current-page="setCurrentPage" ></Pagination>
//初始值定义:
data(){
	return {
			cur: 1, //当前页
        	all: 12,  //
	}
}

//方法
listen: function (data) {
	console.log('当前页码:' + data )
},
// 设置当前页码
setCurrentPage: function(index){
      this.cur = index;
 },
### 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` 变量从而达到动态渲染的效果。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值