vue3 + vite6版本使用new URL(url, import.meta.url).href无法动态获取静态资源的解决方案

无效的代码块(该代码在vite 5版本有效):

/**
 * 获取图片的地址
 * @param path 基于assets/images/文件夹下的位置
 * @returns 图片地址
 */
export function getImageUrl(path: string) {
  return new URL(`../assets/images/${path}`, import.meta.url).href;
}

问题:当资源文件存放在多层文件夹下,此时 path 路径含有多层目录,无法获得资源地址。

例:

此时 path = '404_images/404_cloud.png' 

原因:

vite6相比于vite5,path中不再包括子目录的文件。

解决方案:

<img :src="getImageUrl('404_images/404.png')" alt="404" />
/**
 * 根据图片路径获取图片地址(基于 assets/images 路径)
 * @param path 图片路径
 * @returns 图片地址
 */
export function getImageUrl(path: string) {
  const pathArr = path.split('/');
  switch (pathArr.length) {
    case 1:
      return new URL(`/src/assets/images/${path}`, import.meta.url).href;
    case 2:
      return new URL(`/src/assets/images/${pathArr[0]}/${pathArr[1]}`, import.meta.url).href;
    case 3:
      return new URL(
        `/src/assets/images/${pathArr[0]}/${pathArr[1]}/${pathArr[2]}`,
        import.meta.url
      ).href;
    default:
      throw new Error('Invalid path');
  }
}

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值