将表格二次封装,方便以后开发中的复用。每次只需调用表格组件后,在父组件中往子组件标签上写入dataSource(表格数据)和columns(表格列标题)即可。
此案例中最后一列是删除按钮,动态生成,在父组件中定义columns时用
slots: { customRender: "operation" } 来动态渲染。
在子组件的template标签中通过slot插槽来传值(每一行的值),在父组件中通过v-slot="slotProps"接收子组件传过来的值。
示例代码如下:
子组件MngTable.vue
<template>
<a-table :dataSource="dataSource" :columns="columns">
<template #operation="{ record }">
<slot :record="record"></slot>
</template>
</a-table>
</template>
<script lang="ts">
import { defineComponent } from "vue";
export default defineComponent({
name: "MngTable",
props: {
dataSource: [],
columns: [],
},
components: {},
setup() {
return {};
},
});
</script>
<style lang="scss" scoped></style>
父组件Parent.vue
<template>
<div class="section pitch_default p_default">
<MngTable :dataSource="dataSource" :columns="columns">
<template v-slot="slotProps">
<a-button type="primary">删除</a-button>
</template>
</MngTable>
</div>
</template>
<script lang="ts">
import { defineComponent } from "vue";
import { ManageTable } from "@/components";
export default defineComponent({
name: "Parent",
components: {
ManageTable,
},
setup() {
const pagination = {
total: 200,
current: 1,
pageSize: 10,
};
const columns = [
{
title: "name",
dataIndex: "name",
key: "name",
},
{
title: "age",
dataIndex: "age",
key: "age",
},
{
title: "operation",
key: "operation",
slots: { customRender: "operation" },
},
];
const dataSource = [
{
name: '胡彦斌',
age: 32,
},
{
name: '胡彦祖',
age: 42,
},
],
return {
dataSource,
columns,
pagination,
};
},
});
</script>
<style lang="scss" scoped></style>