封装表格组件,最后一列动态生成 vue3子组件通过slot传值向父组件

将表格二次封装,方便以后开发中的复用。每次只需调用表格组件后,在父组件中往子组件标签上写入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>

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值