返回
Vue 3中巧用组件 封装el-table和el-pagination轻松搞定表格和分页
前端
2024-02-20 03:26:53
好的,这里是一篇关于“在Vue 3中封装el-table和el-pagination”的文章。
当你在一个项目中屡次使用表格和分页的时候,要写一大堆的el-table-column是不是很烦,接下来封装的该组件不仅可以替你减轻代码量,还不用自己再手动加分页,并且表格中支持自定义渲染的内容哦。
首先,我们需要安装必要的依赖:
npm install --save vue3 el-table el-pagination
然后,创建一个新的Vue 3组件。例如,我们称之为TablePagination.vue
。
<template>
<div>
<el-table :data="tableData" :columns="tableColumns"></el-table>
<el-pagination
:current-page="currentPage"
:page-size="pageSize"
:total="tableData.length"
@current-change="handleCurrentChange"
/>
</div>
</template>
<script>
import { defineComponent } from 'vue';
import ElTable from 'el-table';
import ElTableColumn from 'el-table-column';
import ElPagination from 'el-pagination';
export default defineComponent({
name: 'TablePagination',
components: { ElTable, ElTableColumn, ElPagination },
props: {
tableData: {
type: Array,
default: () => [],
},
tableColumns: {
type: Array,
default: () => [],
},
currentPage: {
type: Number,
default: 1,
},
pageSize: {
type: Number,
default: 10,
},
},
methods: {
handleCurrentChange(val) {
this.$emit('current-change', val);
},
},
});
</script>
<style scoped>
.el-table {
width: 100%;
}
</style>
现在,我们可以使用这个组件了。例如,在我们的App.vue
组件中:
<template>
<div>
<TablePagination
:table-data="tableData"
:table-columns="tableColumns"
@current-change="handleCurrentChange"
/>
</div>
</template>
<script>
import { ref } from 'vue';
import TablePagination from './TablePagination.vue';
export default {
components: { TablePagination },
setup() {
const tableData = ref([
{
name: 'John Doe',
age: 30,
address: '123 Main Street',
},
{
name: 'Jane Smith',
age: 25,
address: '456 Elm Street',
},
{
name: 'Michael Jones',
age: 40,
address: '789 Oak Street',
},
]);
const tableColumns = ref([
{
prop: 'name',
label: 'Name',
},
{
prop: 'age',
label: 'Age',
},
{
prop: 'address',
label: 'Address',
},
]);
const handleCurrentChange = (val) => {
console.log(`Current page: ${val}`);
};
return {
tableData,
tableColumns,
handleCurrentChange,
};
},
};
</script>
这样,我们就成功地封装了el-table和el-pagination,并且可以轻松地使用它们了。
希望这篇文章对您有所帮助。如果您有任何问题,请随时留言。