vue3屏幕组件自适应

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

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

export default function screenAdaptiveUtils(screenWidth: Ref, elementWid: Ref, 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
            }
        }
    })
}

你可能感兴趣的:(vue3,vue.js,javascript,前端)