Componentalization
This commit is contained in:
@@ -1,38 +1,16 @@
|
||||
import { onMounted, onBeforeUnmount, nextTick } from 'vue';
|
||||
export interface IntersectionObserverOptions {
|
||||
threshold?: number;
|
||||
rootMargin?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* useIntersectionObserver
|
||||
*
|
||||
* @param selector - CSS selector for elements to observe
|
||||
* @param callback - called when intersection changes
|
||||
* @param options - IntersectionObserver options
|
||||
*/
|
||||
export const useIntersectionObserver = (
|
||||
selector: string,
|
||||
export const createIntersectionObserver = (
|
||||
callback: IntersectionObserverCallback,
|
||||
options: IntersectionObserverInit = {}
|
||||
) => {
|
||||
let observer: IntersectionObserver | null = null;
|
||||
|
||||
const defaultOptions: IntersectionObserverInit = {
|
||||
options: IntersectionObserverOptions = {}
|
||||
): IntersectionObserver => {
|
||||
const defaultOptions: IntersectionObserverOptions = {
|
||||
threshold: 0.3,
|
||||
rootMargin: '0px 0px -50px 0px',
|
||||
rootMargin: '0px 0px -50px 0px'
|
||||
};
|
||||
|
||||
onMounted(async () => {
|
||||
await nextTick(); // wait for DOM to render
|
||||
|
||||
const elements = document.querySelectorAll(selector);
|
||||
if (!elements.length) return;
|
||||
|
||||
observer = new IntersectionObserver(callback, { ...defaultOptions, ...options });
|
||||
elements.forEach(el => observer!.observe(el));
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
if (observer) {
|
||||
observer.disconnect();
|
||||
observer = null;
|
||||
}
|
||||
});
|
||||
return new IntersectionObserver(callback, { ...defaultOptions, ...options });
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user