Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 601
user7011686 Avatar asked Jan 03 '23 12:01

user7011686


1 Answers

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.

like image 196
acdcjunior Avatar answered Jan 05 '23 00:01

acdcjunior