最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Vue.js - Trying to bind dynamic images... what should I do? - Stack Overflow

programmeradmin1浏览0评论

I've started a new project using Vue-CLI 3 and Webpack 4. Everything works fine, but for some reason I'm not able to bind images. The structure that I have is so easy:

<div id="app">
   <div v-for="item in items">
      {{ item.name }}
      <img :src="'../public/images/' + item.img">
   </div>
</div>

And then, my items array. It es from my Store in Vuex.

items = [
   {
      name: 'my-name-1',
      img: 'image-1.png'
   },
   {
      name: 'my-name-2',
      img: 'image-2.png'
   },
   {
      name: 'my-name-3',
      img: 'image-3.png'
   }
]

I've been playing with Webpack, because I guess the problem es from there. I've changed some configurations, I've tested with diferents paths (./, ../, ~/...) but nothing works... What I'm doing wrong? Thanks in advance.

I've started a new project using Vue-CLI 3 and Webpack 4. Everything works fine, but for some reason I'm not able to bind images. The structure that I have is so easy:

<div id="app">
   <div v-for="item in items">
      {{ item.name }}
      <img :src="'../public/images/' + item.img">
   </div>
</div>

And then, my items array. It es from my Store in Vuex.

items = [
   {
      name: 'my-name-1',
      img: 'image-1.png'
   },
   {
      name: 'my-name-2',
      img: 'image-2.png'
   },
   {
      name: 'my-name-3',
      img: 'image-3.png'
   }
]

I've been playing with Webpack, because I guess the problem es from there. I've changed some configurations, I've tested with diferents paths (./, ../, ~/...) but nothing works... What I'm doing wrong? Thanks in advance.

Share Improve this question edited Apr 18, 2018 at 14:13 user7011686 asked Apr 18, 2018 at 13:36 user7011686user7011686 511 silver badge4 bronze badges 3
  • item is out of scope/undefined in img, it's only bound inside the v-for div, therefor <img .. item.img will not work – birdspider Commented Apr 18, 2018 at 13:49
  • Sorry, my fault. Fixed. This doesn't work anyway. – user7011686 Commented Apr 18, 2018 at 13:57
  • well if items = [ is your real code - that its not valid js/json (should be {items : [...]}) - see here for a working demo – birdspider Commented Apr 18, 2018 at 14:00
Add a ment  | 

1 Answer 1

Reset to default 9

To have dynamic image paths, use require():

<img :src="require('../public/images/' + item.img)">



Tip: leave the least variation possible in the require args. So if you know all images will have the extension .png, do:

<img :src="require('../public/images/' + item + '.png')">

Of course, the string item should not have the extension anymore.

This happens because webpack actually parses that require() argument and includes in the bundle all files that may match it. The more specific your arg is, the less files that will never be used will be included in the bundle by webpack.

发布评论

评论列表(0)

  1. 暂无评论