一、技术栈:vue2.X,nuxt项目
二、父组件:
封装前,一些必要的属性和事件需要传,看起来内容很多,在某些场景下也不是很满足项目的要求,下文会提到:
<el-pagination class="pagination" align="right" @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="curPage" :page-sizes="PAGE_NUMBER" :page-size="pageSize" :layout="PAGINATION_LAYOUT" :total="total" />
封装后,仅需传total和查询数据的方法,使用起来很简洁:
pageSizes、layout可以根据需要传递,组件已做默认配置
<m-pagination :total="total" @search="search" ></m-pagination>
search() 方法
// 默认传参page:1, size: 20 // 默认传参后 即使通过表单查询去调用 也可以正常展示 search(page = {page: 1, size: 20}) { console.log('123', page) this.tableLoading = true this.$axios({ method: 'GET', url: `${interfaceaddress}?page=${page.page}&pageSize=${page.size}` }) .then(res => { console.log(res) }) .finally(() => { }) },
三、子组件:
<script> import { Pagination } from 'element-ui'; export default { name: 'MPagination', components: { 'el-pagination': Pagination, }, props: { total: { type: Number, default: 0, }, pageSizes: { type: Array, default: () => [20, 30, 50, 100], }, layout: { type: String, default: 'total, sizes, prev, pager, next, jumper', }, }, data() { return { currentPage: 1, pageSize: 20, }; }, mounted() { console.log('55', this.$attrs) }, methods: { setCurrentPage(page = 1){ this.currentPage = page // 搜索表单的操作希望能高亮显示第一页 } }, render(h) { const Pagination = h( 'el-pagination', { ref: 'pagination', props: { ...this.$attrs, total: this.total, // 分页总数 currentPage: this.currentPage, // 当前页码 pageSize: this.pageSize, // 当前页数量 layout: this.layout, pageSizes: this.pageSizes, }, attrs: { align: 'right' }, on: { 'size-change': pageSize => { // size-change事件时currentPage 赋值为1,避免el-pagination某些场景调用两次查询方法,比如,共有29条数据,每页20条,切换到第二页的时候展示了9条,这是size-change调整为30,此时第二页其实没有数据,el-pagination会再次调用查询方法,page传1 this.pageSize = pageSize this.currentPage = 1 this.$emit('search',{ page: this.currentPage, size: this.pageSize }) }, 'current-change': curPage => { this.currentPage = curPage this.$emit('search',{ page: this.currentPage, size: this.pageSize }) } } }, ); // 没有数据时,不展示分页器 let isBlock = (this.total && this.total > 0) ? 'block' : 'none' return h('div', { class: 'm-pagination', style: { display: isBlock } }, [Pagination]); }, }; </script> <style lang="less"> .m-pagination { // 分页的样式,与表格融为一体 display: flex; justify-content: flex-end; padding-right: 0; background: #fff; padding: 7px 26px 6px 0; border: 1px solid #e6e6e6; border-top: none; border-radius: 0 0 3px 3px; } </style>
四、全局注册
4.1、plugins目录创建文件,plugins.js
import Vue from 'vue'; import MPagination from '../m-components/m-pagination'; Vue.component('MPagination', MPagination);
4.2、在nuxt.config.js引入
plugins: [ { src: '../m-front-common/pc/plugins/plugins' }, ],
4.3、全局注册后即可直接在业务页面使用,无需再次注册
五、效果:
六、遇到问题
6.1、在有的项目引用不到Pagination,那么可以引用全路径:
import Pagination from 'element-ui/lib/pagination';
6.2、使用render开发组件,组件可以注册,也可以直接使用(无需注册)
七、欢迎交流指正,关注我,一起学习!