ant-design-vue/components/_util/Portal.tsx

73 lines
1.6 KiB
Vue
Raw Normal View History

import PropTypes from './vue-types';
import {
defineComponent,
nextTick,
onBeforeMount,
onMounted,
onUpdated,
Teleport,
watch,
} from 'vue';
import { useInjectPortal } from '../vc-trigger/context';
export default defineComponent({
compatConfig: { MODE: 3 },
name: 'Portal',
inheritAttrs: false,
props: {
getContainer: PropTypes.func.isRequired,
didUpdate: Function,
},
setup(props, { slots }) {
2021-12-12 16:47:30 +08:00
let isSSR = true;
// getContainer 不会改变,不用响应式
2021-12-12 16:47:30 +08:00
let container: HTMLElement;
const { shouldRender } = useInjectPortal();
function setContainer() {
if (shouldRender.value) {
container = props.getContainer();
}
}
2021-12-12 16:47:30 +08:00
onBeforeMount(() => {
isSSR = false;
// drawer
setContainer();
});
onMounted(() => {
if (container) return;
// https://github.com/vueComponent/ant-design-vue/issues/6937
setContainer();
});
const stopWatch = watch(shouldRender, () => {
if (shouldRender.value && !container) {
container = props.getContainer();
}
if (container) {
stopWatch();
}
2021-12-12 16:47:30 +08:00
});
onUpdated(() => {
nextTick(() => {
if (shouldRender.value) {
props.didUpdate?.(props);
}
});
});
// onBeforeUnmount(() => {
// if (container && container.parentNode) {
// container.parentNode.removeChild(container);
// }
// });
return () => {
if (!shouldRender.value) return null;
2021-12-12 16:47:30 +08:00
if (isSSR) {
return slots.default?.();
}
return container ? <Teleport to={container} v-slots={slots}></Teleport> : null;
};
},
});