Last active
September 2, 2022 07:35
-
-
Save 0x30/07c902b8cc2c486469cbfc9d63dfd944 to your computer and use it in GitHub Desktop.
vue 动态创建 组件的辅助方法
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 动态弹出视图方法 | |
* | |
* ```ts | |
* const { show, close } = usePopup(); | |
show( | |
<button | |
onClick={async () => { | |
await close(); | |
console.log("leaved."); | |
}} | |
> | |
close | |
</button> | |
); | |
* ``` | |
* | |
* @param options 配置对象,同 Transition,属性 | |
*/ | |
const Popup = (options?: TransitionProps & { root?: Element }) => { | |
/// create document | |
const container = document.createElement("div"); | |
(options?.root ?? document.body).appendChild(container); | |
const isShowRef = ref(false); | |
const componentRef = ref<Component>(); | |
const hiddenModal = () => { | |
isShowRef.value = false; | |
componentRef.value = undefined; | |
}; | |
// 外部调用 promise resolve | |
let __resolve: () => void; | |
const close = () => { | |
return new Promise<void>((resolve) => { | |
__resolve = () => resolve(); | |
hiddenModal(); | |
}); | |
}; | |
const app = createApp(() => ( | |
<Transition | |
{...options} | |
// overwrite onAfterLeave | |
onAfterLeave={(el) => { | |
if (options?.onAfterLeave) { | |
if (typeof options.onAfterLeave === "function") { | |
options.onAfterLeave(el); | |
} else { | |
options.onAfterLeave.forEach((f) => f(el)); | |
} | |
} | |
app.unmount(); | |
document.body.removeChild(container); | |
__resolve?.(); | |
}} | |
> | |
{isShowRef.value ? componentRef.value : null} | |
</Transition> | |
)); | |
const show = (component: Component) => { | |
app.mount(container); | |
componentRef.value = component; | |
isShowRef.value = true; | |
}; | |
return [show, close] as [typeof show, typeof close]; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment