vue2,elementUI表格的二次封装代码
时间: 2023-07-03 09:31:04 浏览: 86
以下是一个简单的 Vue 2 和 Element UI 表格二次封装的示例代码:
```
<template>
<el-table :data="pageData" :default-sort="{prop: 'id', order: 'ascending'}">
<el-table-column label="ID" prop="id" sortable />
<el-table-column label="姓名" prop="name" />
<el-table-column label="年龄" prop="age" />
<el-table-column label="性别" prop="gender" />
<el-table-column label="操作">
<template slot-scope="scope">
<el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
<el-button size="small" @click="handleDelete(scope.row)">删除</el-button>
</template>
</el-table-column>
<el-pagination
:current-page.sync="currentPage"
:page-sizes="[10, 20, 30, 40]"
:page-size="pageSize"
:total="tableData.length"
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
/>
</el-table>
</template>
<script>
export default {
props: {
tableData: {
type: Array,
required: true,
},
pageSize: {
type: Number,
default: 10,
},
},
data() {
return {
currentPage: 1,
};
},
computed: {
pageData() {
const start = (this.currentPage - 1) * this.pageSize;
const end = start + this.pageSize;
return this.tableData.slice(start, end);
},
},
methods: {
handleEdit(row) {
// 编辑操作
console.log('编辑', row);
},
handleDelete(row) {
// 删除操作
console.log('删除', row);
},
handleSizeChange(pageSize) {
this.pageSize = pageSize;
},
handleCurrentChange(currentPage) {
this.currentPage = currentPage;
},
},
};
</script>
```
此示例中,将表格数据和每页显示的数据量通过 props 传入组件。使用计算属性 pageData 计算当前页应该显示的数据。在表格下方添加分页组件,使用 v-model 绑定 currentPage,使用 @size-change 和 @current-change 监听分页组件的事件,调用对应的方法进行相应操作。同时,使用 Element UI 的 el-table-column 组件中的 sortable 属性可以实现列排序。
通过这样的封装,可以使表格组件更加通用、简洁,避免重复的代码编写。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)