vue-hooks-plus
Version:
Vue hooks library
50 lines (49 loc) • 1.17 kB
JavaScript
import { ref, computed, watch, getCurrentScope, onScopeDispose } from "vue";
import { getTargetElement } from "../utils/domTarget";
function useResizeObserver(target, callback, options) {
const { box = "content-box", ...argsOptions } = options != null ? options : {};
const isSupported = ref(window && "ResizeObserver" in window);
let ob;
const modelTargets = computed(
() => Array.isArray(target) ? target.map((curr) => getTargetElement(curr)) : [getTargetElement(target)]
);
const dispose = () => {
if (ob) {
ob.disconnect();
ob = null;
}
};
const watcher = watch(
modelTargets,
(elements) => {
dispose();
if (isSupported.value && window) {
ob = new ResizeObserver(callback);
elements.forEach((curr) => {
curr && ob.observe(curr, {
box,
...argsOptions
});
});
}
},
{
flush: "post",
immediate: true
}
);
const stop = () => {
dispose();
watcher();
};
if (getCurrentScope()) {
onScopeDispose(stop);
}
return {
isSupported,
stop
};
}
export {
useResizeObserver as default
};