关于vue项目中动态引入图片作为背景图遇到的问题

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>
  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值