mirror of
https://github.com/nuxt/nuxt.git
synced 2025-02-01 00:00:29 +00:00
fix: provide a proper wrapper for IO with the comp
This commit is contained in:
parent
caf73523c8
commit
966c17be72
@ -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 }, [
|
||||||
|
h(ClientOnly, undefined, {
|
||||||
|
default: () => {
|
||||||
|
if (isIntersecting.value) {
|
||||||
|
return h(componentLoader, attrs);
|
||||||
|
} else {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
]);
|
||||||
return {
|
|
||||||
intersectionTarget
|
|
||||||
}
|
}
|
||||||
}
|
});
|
||||||
})
|
};
|
||||||
|
Loading…
Reference in New Issue
Block a user