vue二次封装组件
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>
{{ 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>