@oiij/use
Version:
Som Composable Functions for Vue 3
30 lines (28 loc) • 1.13 kB
JavaScript
import { computed, watchEffect } from "vue";
import { useElementSize, useWindowSize } from "@vueuse/core";
//#region src/composables/use-auto-ratio.ts
function useAutoRatio(templateRef, ratio = 1, target) {
const targetElementSize = useElementSize(target);
const windowSize = useWindowSize();
const targetWidth = computed(() => target ? targetElementSize.width.value : windowSize.width.value);
const targetHeight = computed(() => target ? targetElementSize.height.value : windowSize.height.value);
const aspectRatio = computed(() => {
if (targetHeight.value === 0) return Infinity;
return targetWidth.value / targetHeight.value;
});
const width = computed(() => aspectRatio.value > ratio ? targetHeight.value * ratio : targetWidth.value);
const height = computed(() => aspectRatio.value > ratio ? targetHeight.value : targetWidth.value / ratio);
watchEffect(() => {
if (templateRef && templateRef.value) {
templateRef.value.style.width = `${width.value}px`;
templateRef.value.style.height = `${height.value}px`;
}
});
return {
templateRef,
width,
height
};
}
//#endregion
export { useAutoRatio };