当UI库弹窗无法满足自定义需求时,需要我们自己开发简单的弹窗组件。弹窗组件与普通业务组件开发没有太大区别,重点在多弹窗之间的关系控制。例如: 弹窗1,弹窗2 由于触发时机不同,需要不同的层叠关系,后触发的始终在最前端,点击弹窗头改变层叠关系。 单一弹窗多处调用等。这里封装基础的管理钩子,简化这些问题的处理。
功能目标
- 单例,多例弹窗
- 可配置弹窗自定义参数
- 可接收弹窗自定义事件
- 层级控制
- 自定义定位
该钩子的目的主要为了处理弹窗之间的控制关系,具体如何渲染交由调用方
快速使用
// 主容器
import { usePopContainer, buildDefaultPopBind, position } from '@/hooks/usePop'
import UserInfoPop form './UserInfoPop.vue'
// 快捷工具,将内部钩子通过依赖注入,共享给子组件
const [popMap, popTools] = usePopContainer()
const popBind = buildDefaultPopBind(popTools, popTools.componentsCache)
const userPop = popBind('userInfo', UserInfoPop, {position: { // 组件定位top: 200},userId: 'xxx', // 组件porps@close(){ // 组件事件console.log('close')}
})
// 调用
userPop.open()
setTimeout(userPop.close, 1000 * 3)
// template
<template v-for="(pop, popId) of popMap">// 渲染弹窗列表 <component :is="pop.component" :key="popId" v-bind="pop.props" v-on="pop.on" > </component>
</template>
多处调用
同一弹窗,多实例 add
// 容器注册
const [popMap, popTools] = usePopContainer()
// 新增弹窗1
popTools.add(popId1, { component: UserPop, // 弹窗组件 useId: 'xxx', // 弹窗Props '@close': () => { ... } //弹窗事件
})
// 新增弹窗2
popTools.add(popId2, { component: UserPop, // 弹窗组件 useId: 'xxx', // 弹窗Props '@close': () => { ... } //弹窗事件
})
// 覆盖弹窗1
// popId 为弹窗唯一标识, 如果popId相同,组件配置将被替换
popTools.add(popId1, { component: UserPop, // 弹窗组件 useId: 'yyy', // 弹窗Props '@close': () => { ... } //弹窗事件
})
所有弹窗都通过popId,查找or判断唯一性。
配置参数:以
@
开头的都将组为组件的事件被绑定, 除了@[事件名]
component
其他属性都将作为props,包括 style 等属性
移除 remove
const [popMap, popTools] = usePopContainer()
popTools.add(popId, { component: UserPop, // 弹窗组件 useId: 'xxx', // 弹窗Props '@close': () => { ... } //弹窗事件
})
// 移除
popTools.remove(popId)
替换 replace
// 主容器
const [popMap, popTools] = usePopContainer()
// 子组件A
popTools.replace(popId, { component: UserPop, // 弹窗组件 useId: 'xxx', // 弹窗Props '@close': ()