mirror of
https://github.com/youzan/vant.git
synced 2025-10-22 03:44:48 +00:00
36 lines
789 B
TypeScript
36 lines
789 B
TypeScript
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);
|
|
}
|