mirror of
https://gitee.com/vant-contrib/vant.git
synced 2025-04-06 03:57:59 +08:00
feat: add useVisibilityChange
This commit is contained in:
parent
ecb319625b
commit
c9d47204db
35
src/composition/use-visibility-change.ts
Normal file
35
src/composition/use-visibility-change.ts
Normal file
@ -0,0 +1,35 @@
|
|||||||
|
import { inBrowser } from '../utils';
|
||||||
|
import { Ref, onMounted, onUnmounted, onActivated, onDeactivated } from 'vue';
|
||||||
|
|
||||||
|
export function useVisibilityChange(
|
||||||
|
target: Ref<Element>,
|
||||||
|
onChange: () => void
|
||||||
|
) {
|
||||||
|
// compatibility: https://caniuse.com/#feat=intersectionobserver
|
||||||
|
if (!inBrowser || !window.IntersectionObserver) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const observer = new IntersectionObserver(
|
||||||
|
(entries) => {
|
||||||
|
// visibility changed
|
||||||
|
if (entries[0].intersectionRatio > 0) {
|
||||||
|
onChange();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{ root: document.body }
|
||||||
|
);
|
||||||
|
|
||||||
|
const observe = () => {
|
||||||
|
observer.observe(target.value);
|
||||||
|
};
|
||||||
|
|
||||||
|
const unobserve = () => {
|
||||||
|
observer.observe(target.value);
|
||||||
|
};
|
||||||
|
|
||||||
|
onMounted(observe);
|
||||||
|
onActivated(observe);
|
||||||
|
onUnmounted(unobserve);
|
||||||
|
onDeactivated(unobserve);
|
||||||
|
}
|
Loading…
x
Reference in New Issue
Block a user