@oiij/use
Version:
Som Composable Functions for Vue 3
51 lines (49 loc) • 1.35 kB
JavaScript
import { useDebounceFn, useElementSize, useEventListener } from "@vueuse/core";
import { nextTick, ref, watch } from "vue";
//#region src/composables/use-scroll-view.ts
function useScrollView(options) {
const { activeClassName = ".active", enableWheel = true, direction = "vertical" } = options ?? {};
const scrollRef = ref();
const { width, height } = useElementSize(scrollRef);
async function scrollToView(options$1) {
await nextTick();
const activeEl = scrollRef.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":
scrollRef.value?.scrollBy({
top: deltaY > 0 ? height.value : -height.value,
behavior: "smooth"
});
break;
case "horizontal":
scrollRef.value?.scrollBy({
left: deltaY > 0 ? width.value : -width.value,
behavior: "smooth"
});
break;
}
}
useEventListener(scrollRef, "wheel", wheelEvent);
const debouncedScrollToView = useDebounceFn(scrollToView, 500);
watch([width, height], () => {
debouncedScrollToView();
});
return {
scrollRef,
scrollToView
};
}
//#endregion
export { useScrollView };