You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
ant-design-vue/components/_util/Portal.tsx

60 lines
1.4 KiB

import PropTypes from './vue-types';
3 years ago
import {
defineComponent,
nextTick,
onBeforeMount,
onBeforeUnmount,
onUpdated,
Teleport,
watch,
3 years ago
} from 'vue';
import { useInjectPortal } from '../vc-trigger/context';
export default defineComponent({
name: 'Portal',
inheritAttrs: false,
props: {
getContainer: PropTypes.func.isRequired,
didUpdate: PropTypes.func,
},
setup(props, { slots }) {
3 years ago
let isSSR = true;
// getContainer 不会改变,不用响应式
3 years ago
let container: HTMLElement;
const { shouldRender } = useInjectPortal();
3 years ago
onBeforeMount(() => {
isSSR = false;
if (shouldRender.value) {
container = props.getContainer();
}
});
const stopWatch = watch(shouldRender, () => {
if (shouldRender.value && !container) {
container = props.getContainer();
}
if (container) {
stopWatch();
}
3 years ago
});
onUpdated(() => {
nextTick(() => {
if (shouldRender.value) {
props.didUpdate?.(props);
}
});
});
onBeforeUnmount(() => {
if (container && container.parentNode) {
container.parentNode.removeChild(container);
}
});
return () => {
if (!shouldRender.value) return null;
3 years ago
if (isSSR) {
return slots.default?.();
}
return container ? <Teleport to={container} v-slots={slots}></Teleport> : null;
};
},
});