fix: provide a proper wrapper for IO with the comp

This commit is contained in:
Michael Brevard 2024-03-25 19:19:35 +02:00 committed by GitHub
parent caf73523c8
commit 966c17be72
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -1,34 +1,38 @@
import { defineComponent, onMounted, onUnmounted, ref } from 'vue' import { defineComponent, h, ref, onMounted, onBeforeUnmount } from 'vue'
import type { Ref } from 'vue' import type { Component, Ref } from "vue"
import ClientOnly from '#app/components/client-only'
export default defineComponent({ import { useObserver } from "#app/utils"
emits: ['intersect'],
setup (props, { emit }) {
const intersectionTarget: Ref<Element | null> = ref(null)
let observer: IntersectionObserver | null = null
const intersectionCallback: IntersectionObserverCallback = (entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
emit('intersect')
observer!.unobserve(entry.target)
}
})
}
export const createLazyIOClientPage = (componentLoader: Component) => {
return defineComponent({
inheritAttrs: false,
setup (_, { attrs }) {
const isIntersecting = ref(false);
const el: Ref<Element | null> = ref(null);
let unobserve: (() => void) | null = null
onMounted(() => { onMounted(() => {
observer = new IntersectionObserver(intersectionCallback) const observer = useObserver()
observer.observe(intersectionTarget.value as Element) unobserve = observer.observe(el.value as Element, () => {
isIntersecting.value = true
unobserve?.()
unobserve = null
}) })
});
onUnmounted(() => { onBeforeUnmount(() => {
if (observer) { unobserve?.()
observer.disconnect() unobserve = null
}
}) })
return () => h('div', { ref: el }, [
return { h(ClientOnly, undefined, {
intersectionTarget default: () => {
if (isIntersecting.value) {
return h(componentLoader, attrs);
} else {
return null;
} }
} }
}) })
]);
}
});
};