当前位置:   article > 正文

vue3 img图片怎么渲染

vue3 img

Vue3 中加载图片(img)src地址时,出现无法加载问题。网上很多都建议使用 require 加载相对路径,如下:

 <img :src="require('../assets/img/icon.jpg')"/>
  • 1

但是按照这种方式加载又会报错如下:

require is not defined
  • 1

在这里插入图片描述
原因:

Vue3 的 vite 打包中没有 require,Vue低版本是支持require的。

这是因为Vue3早期的低版本采用的还是webpack打包工具。webpack里面是有require的,也是支持require的。

解决方案:

使用import解决,但是又不能直接用,需要使用到new URL,如下:

function targetUrl(name) {
  return new URL(`../${name}.png`, import.meta.url).href
}
  • 1
  • 2
  • 3
<template>
  <div>
    <img v-for="route in routes" :src="targetUrl(route.icon)" :alt="route.name" />
  </div>
</template>

<script setup>
  const routes = ref([
	  { name: 'page1', icon: 'icon1' },
	  { name: 'page2', icon: 'icon2' },
  ]);
  
  function targetUrl(name) {
    return new URL(`../assets/img/${name}.png`, import.meta.url).href;
  }
};
</script>

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/79264
推荐阅读
相关标签
  

闽ICP备14008679号