Vue3的vite中图片的动态加载

第一种方式(适用于处理单个链接的资源文件)

import homeIcon from '@/assets/images/home/home_icon.png'

<img :src="homeIcon" />

第二种方式----- 图片在src目录下

vite官网的静态资源引入参考地址
new URL() + import.meta.url

const getAssetsFile = (url) => {
    
    
   return new URL(`../assets/images/${
      
      url}`, import.meta.url).href
}

注意:这里只能通过 …/…/ 这种方式去获取路径,无法通过@/assets

第三种方式---- 图片在public目录下

/**
 * @description: 动态加载图片 (注意:将图片放到public目录下)
 * @param {*} imgUrl public目录下图片的地址:eg: /public/imgs/a.png, 则imgUrl为 ./imgs/a.png
 * @return {*} 返回图片的绝对路径
 */
const loadPicture = (imgUrl) => {
    
    
	let pathnameArr = location.pathname.split("/");
	let realPathArr = []
	pathnameArr.forEach(item =>{
    
    
		if( item && item.slice(-5) !== '.html'){
    
    
			realPathArr.push(item)
		}
	})
	let realPath = location.origin + "/"
	if(realPathArr.length > 0){
    
    
		realPath = realPath + realPathArr.join('/') + "/"
	}

	return new URL(imgUrl, realPath).href;
}

猜你喜欢

转载自blog.csdn.net/yiyueqinghui/article/details/128545950