天天看點

vue二次封裝元件3個待解決問題前提知識點以封裝Ant Design Vue Table為例

vue二次封裝元件

  • 3個待解決問題
  • 前提知識點
  • 以封裝[Ant Design Vue Table](https://2x.antdv.com/components/table-cn)為例
    • 二次封裝元件
    • 新元件使用
    • 效果圖

3個待解決問題

  1. 屬性傳遞
  2. 事件傳遞
  3. 插槽傳遞

前提知識點

  • Vue的Api文檔:指令v-bind
  • Vue的Api文檔:指令v-on
  • Vue的API文檔:vm.$props
  • Vue的API文檔:vm.$listeners
  • Vue的API文檔:vm.$slots
  • Vue插槽:具名插槽、動态插槽名,作用域插槽、具名插槽的縮寫

以封裝Ant Design Vue Table為例

二次封裝元件

二次封裝元件名為GxTable,簡單的覆寫bordered和pagination屬性,封裝序号列的模闆。

<template>
  <a-table
    v-bind="$props"
    v-on="$listeners"
    :rowKey="(record, index) => index"
  >
    <template #index="{ record, index }">
      <a-checkbox v-model:checked="record.checked"></a-checkbox>
      &nbsp;{{ index + 1 }}
    </template>

    <template v-for="(value, key) in $slots" #[key]="{ text, record, index }">
      <slot :name="key" :text="text" :record="record" :index="index"></slot>
    </template>
  </a-table>
</template>

<script>
import { Table } from 'ant-design-vue';
export default {
  name: 'GxTable',
  props: {
    ...Table.props,
    bordered: {
      type: Boolean,
      default: true,
    },
    pagination: {
      type: Boolean,
      default: false,
    },
  },
};
</script>
           

新元件使用

新元件使用方式和原元件一模一樣,在原元件的基礎上,新元件擴充的屬性或方法或插槽都和普通元件無差別。

<template>
	<GxTable
	  :columns="columns"
	  :dataSource="dataSource"
	>
	  <template #age="{ text }">
	    <a-button type="primary">{{text}}</a-button>
      </template>
    </GxTable>
</template>

<script>
export default {
  name: 'UseGxTableDemo',
  data() {
    return {
      columns: [
        { title: '序号', dataIndex: 'index', width: 80, fixed: 'left', slots: { customRender: 'index' } },
        { title: '姓名', dataIndex: 'name', slots: { customRender: 'name' } },
        { title: '年齡', dataIndex: 'age', slots: { customRender: 'age' } },
      ],
      dataSource: [
        { key: '1', name: '張三瘋', age: 32 },
      ],
    };
  },
};
</script>
           

效果圖

vue二次封裝元件3個待解決問題前提知識點以封裝Ant Design Vue Table為例
vue