故事:
最近接到一个后台管理项目,查看设计图时发现很多组件与AntdV的不一样,全局通过style控制不太好控制,所以就考虑二次封装一下组件,也就是在某某某组件上包括一层, 这样就可以做到有效的管理这些通用的组件, 也可以在组件原有的api基础上开发一些新的属性、方法。。。
环境 & 依赖:
- node
- vue 3.2.0+
- Ant Design Vue 3.2.13
上代码
<template>
<Drawer v-bind="getBindValues">
<!-- 处理antdV Drawer 原有的插槽 -->
<template #[item]="data" v-for="item in Object.keys($slots)">
<slot :name="item" v-if="item !== 'extra'" v-bind="data || {}"></slot>
</template>
<!-- 默认插槽 extra: 抽屉右上角的操作区域 -->
<template #extra>
<close-outlined v-if="!$slots.extra" style="color: #C4C4C4" @click="onCancel"/>
<slot v-else name="extra"></slot>
</template>
</Drawer>
</template>
<script setup lang="ts">
/**
* @作者: 骚男
* @日期: 2022-10-24 21:10:50
* @描述: 抽屉组件二次封装
* @调用示例:
* import BasicDrawer from "@/components/Drawer/src/BasicDrawer.vue";
*
* @参数: 与antdV的Drawer 参数一致
* @API地址: https://www.antdv.com/components/drawer-cn#API
*/
import {CloseOutlined} from "@ant-design/icons-vue";
import {Drawer} from "ant-design-vue";
import {computed, useAttrs, unref, ref, watch, getCurrentInstance, onMounted, defineProps} from "vue";
import {basicProps} from "./props.ts";
const attrs = useAttrs()
// const props = defineProps(basicProps)
const props = defineProps({
// visible: {type: Boolean}
})
const emits = defineEmits(["visible-change", "update:visible"]);
const instance = getCurrentInstance();
onMounted(() => {
console.log(instance)
console.log(props)
})
const onCancel = () => {
emits('update:visible', false)
// visibleRef.value = false
}
const getBindValues = computed(() => {
return {
title: '标题',
closable: false,
bodyStyle: {paddingBottom: '80px'},
...attrs,
// ...unref(getProps),
};
});
</script>
<style scoped>
</style>
插槽问题
既然是二次封装, 官方的所有插槽都是要可以正常使用的
解决方法: $slots
<template #[item]="data" v-for="item in Object.keys($slots)">
<slot :name="item" v-bind="data || {}"></slot>
</template>
注意点: v-bind="data || {}" 绑定官方插槽默认返回的值
API问题
封装的基础上 官方的API都要支持
解决方法: attrs
const getBindValues = computed(() => {
return {
title: '标题', closable: false, bodyStyle: {paddingBottom: '80px'}, ...attrs, // ...unref(getProps),
};
});
我这里是写死了一些默认值
结束语
本篇只是简单封装, 没有扩展什么API,有需要的同学自己自定义扩展。
写的不怎么样, 但是欢迎点赞, 感觉支持!!!