use-visibility-change.mjs 752 B

123456789101112131415161718192021222324252627282930
  1. import { inBrowser } from "../utils/index.mjs";
  2. import { onDeactivated, onBeforeUnmount } from "vue";
  3. import { onMountedOrActivated } from "@vant/use";
  4. function useVisibilityChange(target, onChange) {
  5. if (!inBrowser || !window.IntersectionObserver) {
  6. return;
  7. }
  8. const observer = new IntersectionObserver(
  9. (entries) => {
  10. onChange(entries[0].intersectionRatio > 0);
  11. },
  12. { root: document.body }
  13. );
  14. const observe = () => {
  15. if (target.value) {
  16. observer.observe(target.value);
  17. }
  18. };
  19. const unobserve = () => {
  20. if (target.value) {
  21. observer.unobserve(target.value);
  22. }
  23. };
  24. onDeactivated(unobserve);
  25. onBeforeUnmount(unobserve);
  26. onMountedOrActivated(observe);
  27. }
  28. export {
  29. useVisibilityChange
  30. };