From c9d47204db4d034b0a35be688516aa0eb9afcb05 Mon Sep 17 00:00:00 2001 From: chenjiahan Date: Fri, 28 Aug 2020 11:46:13 +0800 Subject: [PATCH] feat: add useVisibilityChange --- src/composition/use-visibility-change.ts | 35 ++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 src/composition/use-visibility-change.ts diff --git a/src/composition/use-visibility-change.ts b/src/composition/use-visibility-change.ts new file mode 100644 index 000000000..0c5cd57dd --- /dev/null +++ b/src/composition/use-visibility-change.ts @@ -0,0 +1,35 @@ +import { inBrowser } from '../utils'; +import { Ref, onMounted, onUnmounted, onActivated, onDeactivated } from 'vue'; + +export function useVisibilityChange( + target: Ref, + 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); +}