UNPKG

@oiij/use

Version:

Som Composable Functions for Vue 3

50 lines (48 loc) 1.34 kB
import { nextTick, watch } from "vue"; import { useDebounceFn, useElementSize, useEventListener } from "@vueuse/core"; //#region src/composables/use-scroll-view.ts function useScrollView(templateRef, options) { const { activeClassName = ".active", enableWheel = true, direction = "vertical" } = options ?? {}; const { width, height } = useElementSize(templateRef); async function scrollToView(options$1) { await nextTick(); const activeEl = templateRef.value?.querySelector(activeClassName); if (!activeEl) return; activeEl.scrollIntoView({ behavior: "smooth", block: "nearest", inline: "nearest", ...options$1 }); } function wheelEvent(e) { if (!enableWheel) return; e.preventDefault(); const { deltaY } = e; switch (direction) { case "vertical": templateRef.value?.scrollBy({ top: deltaY > 0 ? height.value : -height.value, behavior: "smooth" }); break; case "horizontal": templateRef.value?.scrollBy({ left: deltaY > 0 ? width.value : -width.value, behavior: "smooth" }); break; } } useEventListener(templateRef, "wheel", wheelEvent); const debouncedScrollToView = useDebounceFn(scrollToView, 500); watch([width, height], () => { debouncedScrollToView(); }); return { templateRef, scrollToView }; } //#endregion export { useScrollView };