@stackoverfloweth/vue-compositions
Version:
A collection of reusable vue compositions.
37 lines • 1.41 kB
JavaScript
import { ref, watch } from 'vue';
import { useMutationObserver } from '../useMutationObserver/useMutationObserver';
import { useResizeObserver } from '../useResizeObserver/useResizeObserver';
import { getWindowComputedStyle } from '../utilities/window';
export function useComputedStyle(element) {
const elementRef = ref(element);
const initialStyle = getWindowComputedStyle(elementRef.value);
const style = ref(initialStyle);
function observerCallback([entry]) {
if (nodeIsElement(entry.target)) {
updateStyleRef(entry.target);
}
}
function updateStyleRef(element) {
const computedStyle = getWindowComputedStyle(element);
if (computedStyle) {
style.value = computedStyle;
}
}
const mutationObserver = useMutationObserver(observerCallback);
const resizeObserver = useResizeObserver(observerCallback);
watch(elementRef, element => {
if (element) {
updateStyleRef(element);
mutationObserver.disconnect();
mutationObserver.observe(elementRef, { attributes: true, childList: true });
resizeObserver.disconnect();
resizeObserver.observe(elementRef);
}
}, { immediate: true });
return style;
}
function nodeIsElement(node) {
const element = node;
return !!element.attributes;
}
//# sourceMappingURL=useComputedStyle.js.map