本文主要是介绍vue: render 封装el-pagination,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一、技术栈:vue2.X,nuxt项目
二、父组件:
封装前,一些必要的属性和事件需要传,看起来内容很多,在某些场景下也不是很满足项目的要求,下文会提到:
<el-paginationclass="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 = truethis.$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传1this.pageSize = pageSizethis.currentPage = 1this.$emit('search',{page: this.currentPage,size: this.pageSize})},'current-change': curPage => {this.currentPage = curPagethis.$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开发组件,组件可以注册,也可以直接使用(无需注册)
七、欢迎交流指正,关注我,一起学习!
这篇关于vue: render 封装el-pagination的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!