lovelmh13/myBlog

vue中通过地址遍历图片

Opened this issue · 0 comments

当我们展示很多图片的时候,肯定不能直接都手动写图片所以需要遍历图片

通过require方法来引用图片的src来遍历展示图片。但是要注意,src的写法是有规定的。

假设我们的图片地址是:img/a/aisi@3x.jpg ,我们不能直接在data中直接写这个路径,然后填进require进行遍历:
以下是错误的例子:

<div
  class="toyPic"
  v-for="(toy, index) in toyPic"
  :key="index"
>
  <img
    class="toy"
    :src="require(toy.src)"
  >
</div>

<script>
...
toyPic: [
  {
    src: 'img/a/aisi@3x.jpg,
    name: '艾斯'
  },
]
...
</script>

这样require是不能识别路径的,只会以为是单纯的字符串。 具体原因,应该去看一下require

正确的写法,应该是把路径先在require中写好,我们只传入图片名字,进行拼接就好了

<div
  class="toyPic"
  v-for="(toy, index) in toyPic"
  :key="index"
>
  <img
    class="toy"
    :src="require('img/a/' + toy.src))"
  >
</div>

<script>
...
toyPic: [
  {
    src: 'aisi@3x.jpg,
    name: '艾斯'
  },
]
...
</script>