效果
项目用了nuxt的VUE框架和ElementUI框架,所以有几个步骤
一 定义组件
<template>
<el-pagination
:current-page="pageInfo.current"
:page-size="pageInfo.size"
:total="pageInfo.total"
background
layout="total, prev, pager, next"
@current-change="handleCurrentChange"
@prev-click="handlePrevClick"
@next-click="handleNextClick"/>
</template>
<script>
export default {
name: 'Pagination',
//定义父组件传回的数据
props: {
pageInfo: {
type: Object,
required: true
}
},
watch: {
pageInfo: {
handler: function(newVal, oldVal) {
if (newVal.current === undefined) {
newVal.current = 1
}
},
//深度监听,不然只监听地址而已
deep: true,
immediate: true
}
},
methods: {
//父组件的函数
handleCurrentChange(val) {
//父组件的函数
this.$emit('toPage', val)
},
handlePrevClick() {
if (this.pageInfo.hasPrevious) {
//父组件的函数
this.$emit('toPage', this.pageInfo.current - 1)
}
},
handleNextClick() {
if (this.pageInfo.hasNext) {
//父组件的函数
this.$emit('toPage', this.pageInfo.current + 1)
}
}
}
}
</script>
<style>
</style>
二 在plugins写一个pagination.js
import Vue from 'vue'
import Pagination from '@/components/Pagination.vue'
Vue.component('my-pagination', Pagination)
三 在nuxt.config.js中的plugins位置 引用 pagination.js
// 只看第二行(项目使用了swiper幻灯片)
plugins: [
'~/plugins/pagination.js',
{src: '~/plugins/nuxt-swiper-plugin.js', ssr: false}],
css: [
'swiper/css/swiper.css'
],
四 父组件使用分页组件
//page-info是传到子组件的参数,toPage是子组件调用父组件的自定义函数名
<my-pagination
:page-info="data"
@toPage="getPage"/>
五 父组件定义子组件需要的函数
//teacherApi.getPageList()是一个自己定义的api,向后端请求数据的
// data是一个map,里面应该包含 records,total,size,current,hasNext,hasPrevious
getPage(val) {
teacherApi.getPageList(val, 8).then(res => {
this.data = res.data.data
})
}
注意点:向后端请求数据,返回的数据应该包含 size,current,total,pages,hasNext,hasPrevious,不然组件无数据的。