Vue.js 3:相对路径绑定v-for循环加载图片失败问题求助
Vue中v-for绑定图片路径404的解决方法
问题原因
Vue项目里assets目录下的静态资源会被webpack打包处理,直接写字符串形式的相对路径,webpack不会识别并解析这个路径,导致最终浏览器请求的路径错误,出现404。
可行解决方法
方法1:用require()包裹图片路径
修改你的数组定义,把每个image字段的值用require()包裹,让webpack正确解析资源路径:
img4: [ {image: require('../assets/img/item4/page1/img1.png'), imgindex: 1}, {image: require('../assets/img/item4/page1/img2.jpg'), imgindex: 2}, {image: require('../assets/img/item4/page1/img3.png'), imgindex: 3}, {image: require('../assets/img/item4/page1/img4.png'), imgindex: 4} ]
模板部分不需要改动,保持原来的:src="Image.image"即可。
方法2:将图片移到public目录下
把图片文件移动到项目根目录的public文件夹里(如果没有就新建),然后修改数组里的路径为根路径形式:
img4: [ {image: '/assets/img/item4/page1/img1.png', imgindex: 1}, {image: '/assets/img/item4/page1/img2.jpg', imgindex: 2}, {image: '/assets/img/item4/page1/img3.png', imgindex: 3}, {image: '/assets/img/item4/page1/img4.png', imgindex: 4} ]
public目录下的资源不会被webpack处理,会直接复制到打包后的根目录,所以用根路径就能直接访问。
方法3:提前用import导入图片
先在组件顶部导入需要的图片,再赋值给数组:
import img1 from '../assets/img/item4/page1/img1.png' import img2 from '../assets/img/item4/page1/img2.jpg' import img3 from '../assets/img/item4/page1/img3.png' import img4Pic from '../assets/img/item4/page1/img4.png' // 然后定义数组 img4: [ {image: img1, imgindex: 1}, {image: img2, imgindex: 2}, {image: img3, imgindex: 3}, {image: img4Pic, imgindex: 4} ]
这种方式和require原理类似,都是让webpack提前处理资源路径。
额外优化建议
- v-for循环要加上唯一的
key属性,比如:key="Image.imgindex",避免Vue渲染出现问题:
<Transition name="slide" v-for="Image in img4" :key="Image.imgindex"> <img :src="Image.image" alt="img" v-if="Image.imgindex == imgdex" class="img4"> </Transition>
- 如果是轮播场景,其实可以把
v-for放在img标签上,外层用单个Transition,或者使用TransitionGroup,这样更符合Vue的过渡组件使用规范。
内容的提问来源于stack exchange,提问作者Demo Nomp
相关产品推荐
相关产品推荐

