4

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 comes 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 comes from there. I've changed some configurations, I've tested with diferents paths (./, ../, ~/...) but nothing works... What I'm doing wrong? Thanks in advance.

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 Commented Apr 18, 2018 at 13:49
  • Sorry, my fault. Fixed. This doesn't work anyway. 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 Commented Apr 18, 2018 at 14:00

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

It seems require() is no longer present in the latest vue (3.x) - at least not without additional imports.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.