sard-uniapp
Version:
sard-uniapp 是一套基于 Uniapp + Vue3 框架开发的兼容多端的 UI 组件库
54 lines (53 loc) • 1.76 kB
JavaScript
import { computed, getCurrentInstance, onBeforeUnmount, onMounted, toValue, unref, watch, } from 'vue';
export function useIntersectionObserver(callback, options = {}) {
const instance = getCurrentInstance();
let observer = null;
const selector = computed(() => unref(options.selector));
const root = computed(() => unref(options.root));
const marginTop = computed(() => toValue(options.marginTop) || 0);
const marginBottom = computed(() => toValue(options.marginBottom) || 0);
const disabled = computed(() => toValue(options.disabled));
const createObserver = () => {
if (!selector.value || disabled.value) {
return;
}
observer = uni.createIntersectionObserver(options.instance?.proxy || instance?.proxy, {
thresholds: options.thresholds,
initialRatio: options.initialRatio,
observeAll: options.observeAll,
});
if (root.value) {
observer?.relativeTo(root.value, {
top: marginTop.value,
bottom: marginBottom.value,
});
}
else {
observer?.relativeToViewport({
top: marginTop.value,
bottom: marginBottom.value,
});
}
observer?.observe(selector.value, callback);
};
watch([selector, root, marginTop, marginBottom, disabled], () => {
recreate();
});
const disconnect = () => {
observer?.disconnect();
};
const recreate = () => {
disconnect();
createObserver();
};
onMounted(() => {
createObserver();
});
onBeforeUnmount(() => {
disconnect();
});
return {
recreate,
disconnect,
};
}