vue3加载动态图片
一、动态加载图片

使用new URL(url, import.meta.url)

<template>
    <div class="home">
        <img :src="getImageUrl()" alt="" />
    </div>
</template>
<script lang="ts">
export default {
    name: 'HomeIndex',
    setup() {
        const getImageUrl = () => {
        	// 里面可以根据需求写逻辑
            return new URL('../assets/img/home/container_bg.png', import.meta.url).href;
        };

        return { getImageUrl };
    },
};
</script>
二、动态加载背景图
2.1 style中设置
<template>
    <div
        class="container"
        :style="{
            background: 'url(' + getAssetsFile(true) + ') no-repeat',
            backgroundSize: '100% 100%',
        }"
    ></div>
</template>
<script lang="ts">
export default {
    name: 'HomeIndex',
    setup() {
        const getAssetsFile = (isAlarm: boolean) => {
            const url = isAlarm
                ? '../assets/img/monitor_alarm_bg.png'
                : '../assets/img/monitor_bg.png';
            return new URL(url, import.meta.url).href;
        };

        return { getAssetsFile };
    },
};
</script>
<style lang="scss">
.container {
    width: 300px;
    height: 100px;
}
</style>

2.2 修改class
<template>
    <div :class="['container', isAlarm ? 'monitor_alarm' : 'monitor_normal']"></div>
</template>
<script lang="ts">
import { ref } from 'vue';
export default {
    name: 'HomeIndex',
    setup() {
        const isAlarm = ref(true);
        const getAssetsFile = (isAlarm: boolean) => {
            const url = isAlarm
                ? '../assets/img/monitor_alarm_bg.png'
                : '../assets/img/monitor_bg.png';
            return new URL(url, import.meta.url).href;
        };

        return { getAssetsFile, isAlarm };
    },
};
</script>
<style lang="scss">
.container {
    width: 300px;
    height: 100px;
}
.monitor_normal {
    background: url(@/assets/img/monitor_bg.png) no-repeat;
    background-size: 100% 100%;
}

.monitor_alarm {
    background: url(@/assets/img/monitor_alarm_bg.png) no-repeat;
    background-size: 100% 100%;
}
</style>

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐