vue-hooks-plus
Version:
Vue hooks library
62 lines (61 loc) • 1.63 kB
JavaScript
import { reactive, watch, onMounted, toRefs } from "vue";
import useResizeObserver from "../useResizeObserver";
import useEventListener from "../useEventListener";
import { getTargetElement } from "../utils/domTarget";
function keyisUseElementBoundingReturnTypeKey(key) {
return ["width", "height", "top", "left", "bottom", "right"].includes(key);
}
function useElementBounding(target, options) {
const { reset = true, windowResize = true, windowScroll = true, immediate = true } = options != null ? options : {};
const size = reactive({
width: 0,
height: 0,
top: 0,
left: 0,
bottom: 0,
right: 0
});
const update = () => {
const targetDom = getTargetElement(target);
if (!targetDom) {
if (reset) {
Object.keys(size).forEach((key) => {
if (keyisUseElementBoundingReturnTypeKey(key))
size[key] = 0;
});
}
return;
}
if (targetDom) {
const { width, height, top, left, bottom, right } = targetDom.getBoundingClientRect();
size.width = width;
size.height = height;
size.top = top;
size.left = left;
size.bottom = bottom;
size.right = right;
}
};
if (windowResize) {
useEventListener("resize", update, {
passive: true
});
}
if (windowScroll) {
useEventListener("scroll", update, {
capture: true,
passive: true
});
}
useResizeObserver(target, update);
watch(() => getTargetElement(target), update);
onMounted(() => {
immediate && update();
});
return {
...toRefs(size)
};
}
export {
useElementBounding as default
};