vue3加载动态图片
vue3 动态加载图片
·
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>
更多推荐
已为社区贡献10条内容
所有评论(0)