vue项目中如果需要动态的引入图片作为背景图
vue2项目
图片资源已知,在指定条件下渲染出来。可以使用import或者require
// html部分
<div class="icon" :style="{background: 'url('+imgSrc+')', backgroundSize: '100% 100%'}"></div>
// js部分
import getImgSrc from "./../../assets/svg/icon-qing.svg";
data() {
return {
imgSrc: ''
}
}
mounted() {
if(指定条件) {
this.imgSrc = getImgSrc
}
}
vue3+vite项目
在vue3+vite项目中发现,不能使用require,这是因为在vue3中是通过vite进行打包编译的,而require是webpack中函数,所以在vue3中不能用,而vite官网给出了替代方法new URL
const imgUrl = new URL('./img.png', import.meta.url).href
document.getElementById('hero-img').src = imgUrl
import.meta.url 是一个 ESM 的原生功能,会暴露当前模块的 URL。
但是本人使用new URL时URL也报错了,暂未找到原因,没办法就改用import引入
在vue2或者vue3项目中,都可以使用import来引入图片资源,vue3中使用import引入和上述vue2中一样,不在详述,此处特别说明一种情况,比如,对于需要引入哪个图片,图片名称还未定,需要调接口后才能知道图片名称,此时使用import就不合适了,此时可以使用import()来实现,此处拿获取高德地图的天气信息为例,代码如下:
// html部分
<div class="icon" :style="{background: 'url('+imgSrc+')', backgroundSize: '100% 100%'}"></div>
<script setup>
import {
ref, watch, reactive, onMounted, computed, onBeforeMount, onUnmounted
} from 'vue';
import weathJson from './../../utils/weath.json';// weath.json为天气状态和需要渲染的图片名称的映射集合
const weatherImg = ref('');
const GetLocation = () => {
axios({
url: 'https://restapi.amap.com/v3/ip',
method: 'post',
params: {
key: '高德的key'
},
}).then((res)=> {
getWeathData(res.data.city, res.data.adcode)
}).catch();
}
const getWeathData = (cityName, cityCode) => {
axios({
url: "https://restapi.amap.com/v3/weather/weatherInfo",
method: "GET",
params: {
key: "高德的key",
city: cityCode,
extensions: 'base',
output: "JSON"
},
}).then(function (resp) {
let newData = resp.data.lives[0];
weatherData.value = newData;
if(weathJson[newData.weather]) {
import(`./../../assets/svg/${weathJson[newData.weather]}.svg`).then(res => {
weatherImg.value = res.default
})
}
})
}
onMounted(() => {
GetLocation()
})
</script>