- 一般而言, 在vue中引入图片会使用类似
import slideImg1 from '@/assets/imgs/kenny-eliason-Ak5c5VTch5E-unsplash.jpg'这种方式, 但是当需要引入的图片数量众多的时候, 这么写就非常麻烦了.
- 参考[vite+v3批量一次性引入本地图片(简单做法)]( https://blog.csdn.net/SunFlower914/article/details/133803443#:~:text=vite%2Bv3批量一次性引入本地图片 (简单做法) 1 在assets%2FfileTypes文件夹中将你需要的png图片导入,并使用文件类型来命名图片 (如docx.png) 2 ,%E4%BD%BF%E7%94%A8import.meta.globEager%E5%B0%86assets%2FfileTypes%E4%B8%8B%E6%89%80%E6%9C%89%E7%9A%84png%E5%9B%BE%E7%89%87%E5%BC%95%E5%85%A5%203%20%E9%80%9A%E8%BF%87%E9%81%8D%E5%8E%86Object.keys%20%28files%29%E4%BD%BF%E7%94%A8%E6%AD%A3%E5%88%99%E5%8C%B9%E9%85%8D%E5%87%BA%E6%AF%8F%E4%B8%AA%E5%9B%BE%E7%89%87%E7%9A%84%E5%90%8D%E7%A7%B0%EF%BC%8C%E7%94%A8%E6%96%87%E4%BB%B6%E7%B1%BB%E5%9E%8B%E5%81%9Aname%EF%BC%8C%E6%96%87%E4%BB%B6%E8%B7%AF%E5%BE%84%E5%81%9A%E5%9B%BE%E7%89%87%E8%B7%AF%E5%BE%84%E5%88%9B%E5%BB%BA%E4%B8%80%E4%B8%AA%E6%95%B0%E7%BB%84%204%20%E5%9C%A8img%E5%9B%BE%E6%A0%87%E7%9A%84src%E5%AE%9A%E4%B9%89%E6%96%B9%E6%B3%95%EF%BC%8C%E8%BF%94%E5%9B%9E%E6%96%87%E4%BB%B6%E8%B7%AF%E5%BE%84%E5%8D%B3%E5%8F%AF)的写法
const newsLogoList = ref([])
/* 引入全部的图片 */
async function multipleImport() {
const files = import.meta.glob('@/assets/logo/*.png', { eager: true })
Object.keys(files).forEach((fileName) => {
let fileType = fileName.match(/([^/]*?)\.[^/.]+$/)[1] //用正则匹配出文件名称
newsLogoList.value.push({
name: fileType,
iconSrc: files[fileName].default,
}) // 将读取到的图片地址保存在newsLogoList之中
})
}
multipleImport()
- 这里需要注意的是: 有的文章里使用的是
import.meta.globEager, 这个API在vite5以上的版本中已经被废除, , 使用的会报错Uncaught TypeError: (intermediate value).globEager is not a function, 改为import.meta.glob('*',{eager:true})来引入,
在html中使用数据
<li v-for="(item, index) in 23" :key="item.pk">
<div class="li-container" :style="liStyle(index)">
<div class="front">
<img
:src="newsLogoList[index]?.iconSrc"
alt=""
:title="newsLogoList[index]?.href"
@click="go(newsLogoList[index]?.href)"
@error.once="handleLogoError"
/>
</div>
<div class="back">
<img
:src="newsLogoList[index + 23]?.iconSrc"
alt=""
:title="newsLogoList[index + 23]?.href"
@click="go(newsLogoList[index + 23]?.href)"
@error.once="handleLogoError"
/>
</div>
</div>
</li>