在vue中使用分页,一般都做个封装来全局化,对组件进行复用。
1、封装。(直接copy就可以使用)
在components文件夹下创建一个pagination文件夹,并新建一个文件index.vue,内容如下:
/** index.vue*/
<template>
<div :class="{'hidden':hidden}" class="pagination-container">
<el-pagination
:background="background"
:current-page.sync="currentPage"
:page-size.sync="pageSize"
:layout="layout"
:page-sizes="pageSizes"
:total="total"
v-bind="$attrs"
@size-change="handleSizeChange"
@current-change="handleCurrentChange"/>
</div>
</template>
<script>
import { scrollTo } from '@/utils/scrollTo'
export default {
name: 'Pagination',
props: {
total: {
required: true,
type: Number
},
page: {
type: Number,
default: 1
},
limit: {
type: Number,
default: 20
},
pageSizes: {
type: Array,
default() {
return [10, 20, 30, 50]
}
},
layout: {
type: String,
default: 'total, sizes, prev, pager, next, jumper'
},
background: {
type: Boolean,
default: true
},
autoScroll: {
type: Boolean,
default: true
},
hidden: {
type: Boolean,
default: false
}
},
computed: {
currentPage: {
get() {
return this.page
},
set(val) {
this.$emit('update:page', val)
}
},
pageSize: {
get() {
return this.limit
},
set(val) {
this.$emit('update:limit', val)
}
}
},
methods: {
handleSizeChange(val) {
this.$emit('pagination', { page: this.currentPage, limit: val })
if (this.autoScroll) {
scrollTo(0, 800)
}
},
handleCurrentChange(val) {
this.$emit('pagination', { page: val, limit: this.pageSize })
if (this.autoScroll) {
scrollTo(0, 800)
}
}
}
}
</script>
<style scoped>
.pagination-container {
background: #fff;
padding: 32px 16px;
}
.pagination-container.hidden {
display: none;
}
</style>
2、使用
/**需要用到分页的页面*/
<template>
<!-- 分页 -->
<pagination
v-show="total>0"
:total="total"
:offset.sync="listQuery.queryPage.pageNum"
:limit.sync="listQuery.queryPage.pageSize"
class="pagination-content"
@pagination="getList"
/>
</div>
</template>
<script>
import Pagination from '@/components/Pagination'
import { getAudit } from '@/api/app-audit.js'
export default {
name: 'AppAudit',
components: {
Pagination
},
data() {
return {
auditList: [],
total: 0, // 审计列表总数
listQuery: { // 获取审计列表传参集合
queryPage: {
pageNum: 1, // 当前页
pageSize: 10 // 每页显示条数
}
},
loading: true
}
},
created() {
// 获取审计列表
this.getList()
},
methods: {
// 获取审计列表
getList() {
this.loading = true
const params = {}
params.appId = this.appId // 应用id
params.pageNum = this.listQuery.queryPage.pageNum // 当前页
params.pageSize = this.listQuery.queryPage.pageSize // 每页显示条数
// 对分页进行相关操作的判断
arguments[0] ? (params.pageSize = arguments[0].limit, params.pageNum = arguments[0].page) : params
getAudit(params).then(res => {
this.auditList = res.model
this.total = res.totalCount
this.loading = false
}).catch(err => {
this.loading = false
err.errorMessage ? this.$message.info(err.errorMessage) : this.$message.info('获取审计列表出错啦,请稍后重试!')
})
}
}
}