如何在vue中封装一个Element分页组件,主要有有3个步骤。
1、安装 Element
npm i element-ui -S
在main.js中引入Element
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
Vue.use(ElementUI);
2、封装分页页面。
<template>
<div class="block" :style="{ 'white-space': 'nowrap','padding': '2px 5px','color': '#303133','font-weight': '700','text-align': 'center' }">
<el-pagination
layout="total, sizes, prev, pager, next, jumper"
:total="pager.total"
:current-page.sync="currentPage"
:page-size="pager.rows"
:page-sizes="[20, 30, 40, 50]"
prev-text="上一页"
next-text="下一页"
@size-change="onChangeSize"
@current-change="onChangePage">
</el-pagination>
</div>
</template>
<script>
export default {
name: 'Pagination',
props: ['pager'],
computed: {
total() {
return this.pager.total;
},
// 检测是否获取到无数据
initBack() {
return this.pager.total / this.pager.rows < this.pager.page;
},
},
data() {
return {
currentPage:1
}
},
watch: {
total() {
// 存在记录但未获取到数据时, 重新请求
if (this.initBack) {
this.pager.page -= 1;
this.$emit('change');
}
},
},
mounted() {},
methods: {
// 每页条数
onChangeSize(rows) {
this.pager.rows = rows;
this.$emit('change');
},
// 翻页
onChangePage(page) {
this.pager.page = page;
this.$emit('change');
}
}
}
</script>
3、在需要的列表页码引入组件,传入参数。
页面展示:
<pagination :pager="pager" @change="getItemList"></pagination>
引入组件:
import Pagination from '@/components/Pagination'
components: { Pagination }
传参:
//定义分页对象
pager: {
total: 0,
page: 1,
rows: 20,
},
//传参
queryPageList().then(res => {
const data = res.data;
this.tableData = data.recordList;
this.pager.total=data.totalCount
this.pager.page=data.beginPageIndex
});
把查到的列表数据的数量信息,赋给pager对象,即实现动态传参。
翻页:
getItemList() {
//列表查询
queryPageList().then(res => {
const data = res.data;
this.tableData = data.recordList;
this.pager.total=data.totalCount
this.pager.page=data.beginPageIndex
});
}
以上3步就完成了分页组件的分装,在需要的页面引入,传入相应的参数即可。