vue使用v-for遍历本地图片不显示问题

vue使用v-for遍历本地图片不显示问题

1、项目中本地有一组图片需要循环遍历展示,在使用v-for遍历之后发现无法展示图片,解决方法如下。

2、首先,正常的图片路径如下,但是想要展示不能按正常的来。需要遍历的数据正常情况如下。

   // 重点代办任务数据
      toDoListDate: [
        { id: 1, name: '即将响应超时', number: 20, imgSrc: '../common/img/group1.webp' },
        { id: 2, name: '即将完成超时', number: 21, imgSrc: '../common/img/group2.webp' },
        { id: 3, name: '响应超时', number: 20, imgSrc: '../common/img/group3.webp' },
        { id: 4, name: '完成超时', number: 23, imgSrc: '../common/img/group4.webp' },
        { id: 5, name: '客户催单', number: 25, imgSrc: '../common/img/group7.webp' },
        { id: 6, name: '重新维修', number: 27, imgSrc: '../common/img/group6.webp' },
        { id: 7, name: '暂停任务', number: 0, imgSrc: '../common/img/group5.webp' },
      ],

3、假设使用以下的方法

 <img v-for= "item in toDoListDate" :key = "item.id" :src="item.imgSrc"alt="" srcset="">
这种做法拿不到本地图片,原因不明,但是有解决方法。

4、解决方法如下,在导入路径时使用 require

  • 4.1、这里需要改变以下需要遍历数据的本地图片地址,本质其实就是把图片地址拆成两节,使用 require 拼接。先修改本地需遍历的数据,如下。
    // 重点代办任务数据
      toDoListDate: [
        { id: 1, name: '即将响应超时', number: 20, imgSrc: 'img/group1.webp' },
        { id: 2, name: '即将完成超时', number: 21, imgSrc: 'img/group2.webp' },
        { id: 3, name: '响应超时', number: 20, imgSrc: 'img/group3.webp' },
        { id: 4, name: '完成超时', number: 23, imgSrc: 'img/group4.webp' },
        { id: 5, name: '客户催单', number: 25, imgSrc: 'img/group7.webp' },
        { id: 6, name: '重新维修', number: 27, imgSrc: 'img/group6.webp' },
        { id: 7, name: '暂停任务', number: 0, imgSrc: 'img/group5.webp' },
      ],
  • 4.2、这里可以发现后面的图片路径地址少了一截,这里对比一下少了啥。
  • 这是之前的
{ id: 1, name: '即将响应超时', number: 20, imgSrc: '../common/img/group1.webp' },
  • 这是修改后的
{ id: 1, name: '即将响应超时', number: 20, imgSrc: 'img/group1.webp' },
  • 我们会发现少了…/common/这个片段,那个片段去哪儿?后面使用require会用到。

5、修改本地需要遍历的数据之后,我们再去需改遍历图片的代码。我们对比一下前后的代码,

  • 5.1、只是未修改的。
<img v-for= "item in toDoListDate" :key = "item.id" :src="item.imgSrc"alt="" srcset="">
  • 这是修改后的
<img v-for= "item in toDoListDate" :key = "item.id" :src="require('../common/'+item.imgSrc)" alt="" srcset="">
  • 5.2、我们会发现这里的图片地址发生了明显的变化。
  • 之前是:src=“item.imgSrc” 之后是:src=“require(’…/common/’+item.imgSrc)”
    由此我们知道之前的本地需要遍历的数据里面少的…/common/这个片段是加在了这里。
    使用了require将被拆开的图片地址再次拼接起来。这样就可以遍历展示本地图片了。

6、注意事项

  • 这里我们在拆分图片路径地址时,应该注意一边的固定不变的,一边是动态的。比如这里的…/common/就是不变的,后面的地址会动态变动,因此提出…/common/放在require里面。
上一篇:在html中如何兼容使用WebP格式的图片【图片升级到WebP】


下一篇:前端性能优化学习笔记——网络篇