我采用的vite构建的vue3项目,没有require命令动态引入本地图片,
引入图片方法如下: 仅供参考
方式1,无法动态
import emptyImage from '@/assets/home/yd_4.png'
<img :src="emptyImage" class="h-50 w-50" />
方法2,正常调用,传参可以v-for来获取动态的
const getFilePath = (url: string) => {
console.log('🚀 ~ getFilePath ~ url:', url)
let imgH = new URL(`/src/assets/home/${url}`, import.meta.url).href
console.log('🚀 ~ getFilePath ~ imgH:', imgH)
return imgH
}
<img :src="getFilePath('yd_4.png')" />
在项目中用的是芋道框架改版的,用上面的方案会出现undefined,由于import.meta.url返回的是包含查询参数的完整 URL,可能会导致路径拼接时出现错误。window.location来获取当前页面的URL路径
解决
getFilePath(url) {
console.log('接收', url, 'SSS', window.location.href);
let img = new URL(`/src/assets/images/${url}`, window.location.href).href;
console.log('返回', img);
return img;
},