elementui table二次封装加分页
时间: 2025-02-13 12:39:57 浏览: 49
### ElementUI 表格组件二次封装实现分页
为了对 ElementUI 的表格组件进行二次封装并添加分页功能,可以创建一个新的 Vue 组件来扩展原生的 `el-table` 和 `el-pagination` 功能。这不仅提高了代码复用率还增强了可维护性。
#### 创建自定义表格组件
通过组合方式引入必要的子组件,并利用 props 来传递数据以及事件监听器给内部使用的 element-ui 组件[^1]:
```vue
<template>
<div class="custom-table">
<!-- Table -->
<el-table :data="paginatedData" v-bind="$attrs" @selection-change="handleSelectionChange">
<slot></slot> <!-- 插槽用于放置列定义 -->
</el-table>
<!-- Pagination -->
<el-pagination
layout="total, sizes, prev, pager, next"
:current-page.sync="currentPage"
:page-size.sync="pageSize"
:total="totalCount"
@size-change="handleSizeChange"
@current-change="handleCurrentPageChange"
/>
</div>
</template>
<script>
export default {
name: 'CustomTable',
inheritAttrs: false,
data() {
return {
currentPage: 1,
pageSize: 10,
totalCount: this.data.length || 0
};
},
computed: {
paginatedData() {
const start = (this.currentPage - 1) * this.pageSize;
const end = start + this.pageSize;
if (!Array.isArray(this.data)) return [];
return this.data.slice(start, end);
}
},
watch: {
data(newVal) {
this.totalCount = newVal ? newVal.length : 0;
}
},
methods: {
handleSizeChange(size) {
this.pageSize = size;
this.$emit('pagination', { page: this.currentPage, limit: this.pageSize });
},
handleCurrentPageChange(page) {
this.currentPage = page;
this.$emit('pagination', { page: this.currentPage, limit: this.pageSize });
},
handleSelectionChange(selection) {
this.$emit('update:selectedRows', selection); // 自定义事件名
}
},
props: ['data'] // 接收父级传入的数据源
};
</script>
```
此模板中包含了两个主要部分:一个是基于 prop 数据渲染出来的 el-table 实例;另一个则是负责处理翻页逻辑的 el-pagination 控件。同时提供了插槽支持以便使用者能够灵活定制表头和单元格样式[^2]。
阅读全文
相关推荐


















