vite_在项目中批量引入图片

发布时间 2024-01-11 08:56:09作者: Lei0906
  • 一般而言, 在vue中引入图片会使用类似import slideImg1 from '@/assets/imgs/kenny-eliason-Ak5c5VTch5E-unsplash.jpg'这种方式, 但是当需要引入的图片数量众多的时候, 这么写就非常麻烦了.
  • 参考vite+v3批量一次性引入本地图片(简单做法)的写法

使用import.meta.glob来批量引入图片

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>