feat: add useVisibilityChange

This commit is contained in:
chenjiahan 2020-08-28 11:46:13 +08:00
parent ecb319625b
commit c9d47204db

View 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);
}