2021-10-03 05:30:50 +00:00
|
|
|
import PropTypes from './vue-types';
|
2021-12-12 08:47:30 +00:00
|
|
|
import {
|
|
|
|
defineComponent,
|
|
|
|
nextTick,
|
|
|
|
onBeforeMount,
|
|
|
|
onBeforeUnmount,
|
|
|
|
onUpdated,
|
|
|
|
Teleport,
|
2022-01-07 08:16:11 +00:00
|
|
|
watch,
|
2021-12-12 08:47:30 +00:00
|
|
|
} from 'vue';
|
2022-01-07 08:16:11 +00:00
|
|
|
import { useInjectPortal } from '../vc-trigger/context';
|
2021-10-03 05:30:50 +00:00
|
|
|
|
|
|
|
export default defineComponent({
|
|
|
|
name: 'Portal',
|
|
|
|
inheritAttrs: false,
|
|
|
|
props: {
|
|
|
|
getContainer: PropTypes.func.isRequired,
|
|
|
|
didUpdate: PropTypes.func,
|
|
|
|
},
|
|
|
|
setup(props, { slots }) {
|
2021-12-12 08:47:30 +00:00
|
|
|
let isSSR = true;
|
2021-10-03 05:30:50 +00:00
|
|
|
// getContainer 不会改变,不用响应式
|
2021-12-12 08:47:30 +00:00
|
|
|
let container: HTMLElement;
|
2022-01-07 08:16:11 +00:00
|
|
|
const { shouldRender } = useInjectPortal();
|
2021-12-12 08:47:30 +00:00
|
|
|
onBeforeMount(() => {
|
|
|
|
isSSR = false;
|
2022-01-07 08:16:11 +00:00
|
|
|
if (shouldRender.value) {
|
|
|
|
container = props.getContainer();
|
|
|
|
}
|
|
|
|
});
|
|
|
|
const stopWatch = watch(shouldRender, () => {
|
|
|
|
if (shouldRender.value && !container) {
|
|
|
|
container = props.getContainer();
|
|
|
|
}
|
|
|
|
if (container) {
|
|
|
|
stopWatch();
|
|
|
|
}
|
2021-12-12 08:47:30 +00:00
|
|
|
});
|
2021-10-03 05:30:50 +00:00
|
|
|
onUpdated(() => {
|
|
|
|
nextTick(() => {
|
2022-01-07 08:16:11 +00:00
|
|
|
if (shouldRender.value) {
|
|
|
|
props.didUpdate?.(props);
|
|
|
|
}
|
2021-10-03 05:30:50 +00:00
|
|
|
});
|
|
|
|
});
|
|
|
|
onBeforeUnmount(() => {
|
|
|
|
if (container && container.parentNode) {
|
|
|
|
container.parentNode.removeChild(container);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
return () => {
|
2022-01-07 08:16:11 +00:00
|
|
|
if (!shouldRender.value) return null;
|
2021-12-12 08:47:30 +00:00
|
|
|
if (isSSR) {
|
|
|
|
return slots.default?.();
|
|
|
|
}
|
2021-10-03 05:30:50 +00:00
|
|
|
return container ? <Teleport to={container} v-slots={slots}></Teleport> : null;
|
|
|
|
};
|
|
|
|
},
|
|
|
|
});
|