【前端】Vite项目图片动态引入

我采用的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;
    },

相关推荐

  1. 前端Vite项目图片动态引入

    2024-03-20 17:38:02       41 阅读
  2. Vue3 + Vite项目使用SVG图片

    2024-03-20 17:38:02       22 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-20 17:38:02       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-20 17:38:02       100 阅读
  3. 在Django里面运行非项目文件

    2024-03-20 17:38:02       82 阅读
  4. Python语言-面向对象

    2024-03-20 17:38:02       91 阅读

热门阅读

  1. S&P 2023

    2024-03-20 17:38:02       33 阅读
  2. 【C++】struct和class区别

    2024-03-20 17:38:02       41 阅读
  3. git相关指令

    2024-03-20 17:38:02       38 阅读
  4. Linux dts list python tool

    2024-03-20 17:38:02       35 阅读
  5. leetcode2312--卖木头块

    2024-03-20 17:38:02       40 阅读
  6. 如何理解AI Agent

    2024-03-20 17:38:02       43 阅读