vue3封裝自己的分頁元件
阿新 • • 發佈:2021-09-29
本文例項為大家分http://www.cppcns.com享了3封裝自己分頁元件的具體程式碼,供大家參考,具體內容如下
背景
在瀏覽列表型別的資料的時候,如果資料比較多一次性全部請求會出現效能損耗以及載入延遲等問題,那麼此時分頁元件就起到了關鍵作用,它可以只請求一部分資料,也不會佔用太多的頁面空間,想看別的資料可以通過頁碼的改變來發起請求,重新整理頁面資料
現在我們自己來封裝分頁元件
元件所需引數
- total 屬性 :用來傳遞資料總條數
- pagesize 屬性 :每頁展示幾條資料
- currentPage 屬性 :當前預設頁碼
- change-page 事件 :頁碼改變時觸發的事件,引數為當前頁碼
元件落地程式碼my-pagination.vue
<template> <div class="my-pagination"> <a href=":;" :class="{ disabled: currentPage === 1 }" @click="changePage(false)">上一頁</a> <span v-if="currentPage > 3">...</span> <a href="script:;" v-for="item in list" :key="item" :class="{ active: currentPage === item }" @click="changePage(item)" >{{ item }}</a > <span v-if="currentPage < pages - 2">...</span> <a href="javascript:;" :class="{ disabled: currentPage === pages }" @click="changePage(true)">下一頁</a> </div> </template> <script> import { computed,ref } from 'vue-demi' export default { name: 'MyPagination',props: { total: { type: Number,default: 80 },pagesize: {type: Number,default: 10 } },setup(props,{ emit,attrs }) { // 當前頁 const currentPage = ref(attrs.currentPage) // 計算總頁數 const pages = computedwww.cppcns.com(() => Math.ceil(props.total / props.pagesize)) // 頁碼顯示組合 const list = computed(() => { const result = [] // 總頁數小於等於5頁的時候 if (pages <= 5) { for (let i = 1; i <= pages; i++) {http://www.cppcns.comresult.push(i) } } else { // 總頁數大於5頁的時候 // 控制兩個極端那邊的省略號的有無,頁碼的顯示個數與選中頁碼居中 if (currentPage.value <= 2) { for (let i = 1; i <= 5; i++) { result.push(i) } } else if (currentPage.value >= 3 && currentPage.value <= pages.value - 2) { for (let i = currentPage.value - 2; i <= currentPage.value + 2; i++) { result.push(i) } } else if (currentPage.value > pages.value - 2) { for (let i = pages.value - 4; i <= pages.value; i++) { result.push(i) } } } return result }) // 點選上一頁下一頁頁碼改變頁碼 const changePage = type => { // 點選上一頁按鈕 if (type === false) { if (currentPage.value <= 1) return currentPage.value -= 1 } else if (type === true) { // 點選下一頁按鈕 if (currentPage.value >= pages.value) return currentPage.value += 1 } else { // 點選頁碼 currentPage.value = type } // 傳給父元件當前頁碼,可以在該事件中做相關操作 emit('change-page',currentPage.value) } return { currentPage,pages,list,changePage } } } </script> <style scoped lang="less"> .my-pagination { display: flex; justify-content: center; padding: 30px; > a { display: inline-block; padding: 5px 10px; border: 1px solid #e4e4e4; border-radius: 4px; margin-right: 10px; &:hover { color: @xtxColor; } &.active { background: @xtxColor; color: #fff; border-color: @xtxColor; } &.disabled { cursor: not-allowed; opacity: 0.4; &:hover { color: #333; } } } > span { margin-right: 10px; } } </style>
使用元件
<XtxPagination :total="total" :pagesize="reqParams.pagesize" :currentPage="1" @change-page="changePage" />
效果
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。