Pref hooks (#113)

* pref: replace useContainerResize

* pref: replace useContainerScroll
This commit is contained in:
Hayden
2025-02-02 19:54:23 +08:00
committed by GitHub
parent f079d8bde5
commit faf4c15865
6 changed files with 11 additions and 116 deletions

View File

@@ -1,4 +1,4 @@
import { useContainerResize } from 'hooks/resize'
import { useElementSize } from '@vueuse/core'
import { type InjectionKey, type Ref, inject, provide, toRef } from 'vue'
const rem = parseFloat(getComputedStyle(document.documentElement).fontSize)
@@ -14,7 +14,7 @@ export const useContainerQueries = (
provide(containerKey, container)
const { width } = useContainerResize(container)
const { width } = useElementSize(container)
/**
* @param size unit rem

View File

@@ -1,44 +0,0 @@
import { throttle } from 'lodash'
import { type Ref, onUnmounted, ref, toRef, watch } from 'vue'
export const useContainerResize = (
el: HTMLElement | null | Ref<HTMLElement | null>,
) => {
const observer = ref<ResizeObserver | null>(null)
const width = ref(0)
const height = ref(0)
watch(
toRef(el),
(el) => {
if (el) {
const onResize = throttle((entries: ResizeObserverEntry[]) => {
const entry = entries[0]
width.value = entry.contentRect.width
height.value = entry.contentRect.height
}, 64)
observer.value = new ResizeObserver(onResize)
observer.value.observe(el)
}
},
{ immediate: true },
)
const stop = () => {
if (observer.value) {
observer.value.disconnect()
}
}
onUnmounted(() => {
stop()
})
return {
width,
height,
stop,
}
}

View File

@@ -1,58 +0,0 @@
import { throttle } from 'lodash'
import { computed, onUnmounted, ref, toRef, watch, type Ref } from 'vue'
export interface UseScrollOption {
throttle?: number
onScroll?: (e: Event) => void
}
export const useContainerScroll = (
el: HTMLElement | null | Ref<HTMLElement | null>,
options?: UseScrollOption,
) => {
const scrollLeft = ref(0)
const scrollTop = ref(0)
const container = toRef(el)
const onScroll = throttle((e: Event) => {
options?.onScroll?.(e)
if (container.value) {
scrollLeft.value = container.value.scrollLeft
scrollTop.value = container.value.scrollTop
}
}, options?.throttle ?? 64)
watch(
container,
(el) => {
if (el) {
el.addEventListener('scroll', onScroll, { passive: true })
}
},
{ immediate: true },
)
const x = computed({
get: () => scrollLeft.value,
set: (val) => {
container.value?.scrollTo({ left: val })
},
})
const y = computed({
get: () => scrollTop.value,
set: (val) => {
container.value?.scrollTo({ top: val })
},
})
onUnmounted(() => {
if (container.value) {
container.value.removeEventListener('scroll', onScroll)
}
})
return { x, y }
}