Vue3封装 page 分页组件
实现效果
分页组件封装 page.vue
<template>
<div class="pagination">
<a @click='changePage(false)' href="javascript:;">上一页</a>
<span v-if='currentPage > 3'>...</span>
<a @click='changePage(item)' href="javascript:;" :class='{active: currentPage===item}' v-for='item in list' :key='item'>{{item}}</a>
<span v-if='currentPage < pages - 2'>...</span>
<a @click='changePage(true)' href="javascript:;" :class='{disabled: currentPage===pages}'>下一页</a>
</div>
</template>
<script>
import { computed, ref } from 'vue'
export default {
name: 'Pagination',
props: {
total: {
type: Number,
default: 80
},
pagesize: {
type: Number,
default: 8
}
},
setup (props, { emit, attrs }) {
const pages = computed(() => Math.ceil(props.total / props.pagesize))
const currentPage = ref(attrs.page || 1)
const list = computed(() => {
const result = []
if (pages.value <= 5) {
for (let i = 1; i <= pages.value; i++) {
result.push(i)
}
} else {
if (currentPage.value <= 2) {
for (let i = 1; i <= 5; i++) {
result.push(i)
}
} else if (currentPage.value >= pages.value - 1) {
for (let i = pages.value - 4; i <= pages.value; i++) {
result.push(i)
}
} else {
for (let i = currentPage.value - 2; i <= currentPage.value + 2; i++) {
result.push(i)
}
}
}
return result
})
const changePage = (type) => {
if (type === false) {
if (currentPage.value === 1) return
if (currentPage.value > 1) {
currentPage.value -= 1
}
} else if (type === true) {
if (currentPage.value === pages.value) return
if (currentPage.value < pages.value) {
currentPage.value += 1
}
} else {
currentPage.value = type
}
emit('change-page', currentPage.value)
}
return { list, currentPage, pages, changePage }
}
}
</script>
<style scoped lang="less">
.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:#27BA9B;
}
&.active {
background: #27BA9B;
color: #fff;
border-color: #27BA9B;
}
&.disabled {
cursor: not-allowed;
opacity: 0.4;
&:hover {
color: #333;
}
}
}
> span {
margin-right: 10px;
}
}
</style>
父组件引用
<Page @change-page='changePage' :pagesize='pageSize' :total='total' :page='1' />
import { ref } from 'vue
setup(){
const total=ref(0)
const pageSize=ref(10)
const changePage = (page) => {
重新调用接口,渲染数据
}
return{changePage, total ,pageSize}
}