Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(useElementVisibility): support watch the real element #2169

Merged
merged 4 commits into from Sep 5, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
19 changes: 12 additions & 7 deletions packages/core/useElementVisibility/index.ts
@@ -1,7 +1,7 @@
import type { MaybeComputedRef } from '@vueuse/shared'
import { resolveUnref, tryOnMounted } from '@vueuse/shared'
import { ref } from 'vue-demi'
import { ref, watch } from 'vue-demi'
import type { MaybeComputedElementRef } from '../unrefElement'
import { unrefElement } from '../unrefElement'
import { useEventListener } from '../useEventListener'
import type { ConfigurableWindow } from '../_configurable'
import { defaultWindow } from '../_configurable'
Expand All @@ -28,12 +28,12 @@ export function useElementVisibility(
return

const document = window.document
const el = resolveUnref(element)
const el = unrefElement(element)
if (!el) {
elementIsVisible.value = false
}
else {
const rect = (el as HTMLElement).getBoundingClientRect()
const rect = el.getBoundingClientRect()
elementIsVisible.value = (
rect.top <= (window.innerHeight || document.documentElement.clientHeight)
&& rect.left <= (window.innerWidth || document.documentElement.clientWidth)
Expand All @@ -43,11 +43,16 @@ export function useElementVisibility(
}
}

tryOnMounted(testBounding)
watch(
() => unrefElement(element),
() => testBounding(),
{ immediate: true, flush: 'post' },
)

if (window) {
tryOnMounted(() => useEventListener(
() => resolveUnref(scrollTarget) || window, 'scroll', testBounding, { capture: false, passive: true }))
useEventListener(scrollTarget || window, 'scroll', testBounding, {
capture: false, passive: true,
})
}

return elementIsVisible
Expand Down