Vue 组件封装
组件二次封装
背景
基于 Ant Design of Vue 组件库的二次封装
简单情况
封装的属性和方法较少时:
vue
<template>
<a-button
:type="type"
:size="size"
:danger="danger"
:loading="loading"
:disabled="disabled"
:ghost="ghost"
>
<slot></slot>
</a-button>
</template>
<script setup lang="ts">
defineProps<{
type?: 'primary' | 'dashed' | 'link' | 'text' ,
size?: 'small' | 'middle' | 'large',
danger?: boolean,
loading?: boolean,
disabled?: boolean,
ghost?: boolean
}>();
</script>vue
<template>
<a-switch
v-model:checked="modelValue"
:checked-children="checkedChildren"
:un-checked-children="unCheckedChildren"
:disabled="disabled"
:loading="loading"
:size="size"
></a-switch>
</template>
<script setup lang="ts">
import { computed } from 'vue';
const props = defineProps<{
checked: boolean,
checkedChildren?: string,
unCheckedChildren?: string,
disabled?: boolean,
loading?: boolean,
size?: 'default' | 'small'
}>()
const emit = defineEmits<{
(e: 'update:checked', value: boolean): void
(e: 'change', value: boolean): void
}>()
const modelValue = computed({
get: () => props.checked,
set: (val: boolean) => {
emit('update:checked', val)
emit('change', val)
},
})
</script>完整封装
调用时只改变组件名,用法严格与官方一致:
- 最佳应用场景:多组件库切换
- 使用 ts 导入、导出
ts
// 伪代码
import { Button } from 'ant-design-vue'
import { ElButton } from 'element-plus'
if (使用 Antd) {
const MyButton = Button
// 如果有子组件
const MyButtonGroup = Button.Group
}
if (使用 Element) {
const MyButton = ElButton
// 如果有子组件
const MyButtonGroup = ElButton.Group
}
export { MyButton, MyButtonGroup }