vue3屏幕组件自适应

import {onMounted, ref, Ref, watch} from "vue";

/**
 * 屏幕自适应工具类
 * @param screenWidth 屏幕当前宽度
 * @param elementWid 元素宽度
 * @param eleWidth 存放元素宽度的数组
 * @param limtWidth 存放划分屏幕宽度界限的数组
 */

export default function screenAdaptiveUtils(screenWidth: Ref<number>, elementWid: Ref<number>, eleWidth: number[], limtWidth: number[]) {
    onMounted(() => {
        screenWidth.value = document.body.clientWidth
    })
    watch(screenWidth, (newValue) => {
        window.addEventListener('resize', () => {
            return (() => {
                screenWidth.value = document.body.clientWidth
            })();
        })
        if (screenWidth.value >= limtWidth[limtWidth.length - 1]) {
            elementWid.value = eleWidth[eleWidth.length - 1]
        }

        if (screenWidth.value <= limtWidth[0]) {
            elementWid.value = eleWidth[0]
        }
        for (let i = 0; i < eleWidth.length; i++) {
            if (screenWidth.value >= limtWidth[i] && screenWidth.value <= limtWidth[i + 1]) {
                elementWid.value = eleWidth[i]
                break
            }
        }
    })
}

猜你喜欢

转载自blog.csdn.net/Yajyaj123/article/details/127227775