Skip to content

Instantly share code, notes, and snippets.

@0x30
Created October 29, 2020 09:14
Show Gist options
  • Save 0x30/be93dca9bdb154bfd3b5988649c897f5 to your computer and use it in GitHub Desktop.
Save 0x30/be93dca9bdb154bfd3b5988649c897f5 to your computer and use it in GitHub Desktop.
vue3 动态加载模块 并且设置进入和离开动画 可以统一管理这些弹出框
import {
Component,
createApp,
defineComponent,
onMounted,
PropType,
ref,
Transition
} from "vue";
const popupPools: (() => void)[] = [];
/**
* 装载组件,并且设置动画
*
* @param component 组件
* @param enterAnimed 进入动画
* @param leaveAnimed 退出动画
*/
export const useMountComponentAndAnimed = (params: {
component: Component;
ignorePopupManager?: boolean;
enterAnimed?: (el: Element, done: () => void) => void;
leaveAnimed?: (el: Element, done: () => void) => void;
}) => {
const { component, enterAnimed, leaveAnimed } = params;
/// create document
const container = document.createElement("div");
document.body.appendChild(container);
/// create modal component
const Modal = defineComponent({
props: {
close: Function as PropType<(method: () => void) => void>,
destory: Function as PropType<() => void>
},
setup: ({ close, destory }) => {
const isShowRef = ref(false);
/// close is not unfined
close!(() => (isShowRef.value = false));
onMounted(() => (isShowRef.value = true));
return () => (
<Transition
onEnter={enterAnimed}
onLeave={leaveAnimed}
onAfterLeave={destory}
>
{isShowRef.value ? component : null}
</Transition>
);
}
});
/// replace the method later
let closeMethod = () => {};
const Component = (
<Modal
style={{ zIndex: 20 }}
close={(method) => (closeMethod = method)}
destory={() => {
app.unmount(container);
document.body.removeChild(container);
}}
></Modal>
);
const app = createApp(Component);
app.mount(container);
if (params.ignorePopupManager !== true) popupPools.push(closeMethod);
return () => {
if (params.ignorePopupManager !== true) popupPools.pop();
closeMethod();
};
};
/// return true 说明页面可以反悔
/// return false 说明页面不可返回
export const useCheckBeforeEach = () => {
if (popupPools.length <= 0) return true;
const close = popupPools.pop();
close && close();
return false;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment