6

I have structure file in vue js like this:

--assets
----image
------my-image.png
------my-image2.png

--components
----user
------userStart.vue

I will show the image using object in array here is my code (userStart.vue)

<img v-for="image in images" :src="image.url"/>

export default{
  data(){
    return {
      images : [
         {
            url : '../../assets/image/my-image.png',
            name : 'My Image 1',
         },
         {
            url : '../../assets/image/my-image1.png',
            name : 'My Image 2'
         }
      ]
    }
  }
}

The problem is I cannot show the image, how to fix it? Thank you

dedi wibisono
  • 511
  • 5
  • 12
  • 23
  • 1
    If you're not importing the image file, that URL isn't relative to the current file - it's relative the root of the served directory. Which directory are you serving your static assets from? – Sam Holmes Sep 16 '18 at 10:44
  • Are you using vue-cli? If so, which version? – Phil Sep 16 '18 at 13:21
  • yes, I using vue-cli 2.9.6 – dedi wibisono Sep 16 '18 at 13:41
  • 1
    @Sanjay below is correct in that you have to use `require` but in your JS, not in your template. See some of the answers here ~ https://stackoverflow.com/questions/47313165/how-to-reference-static-assets-within-vue-javascript?answertab=votes#tab-top – Phil Sep 16 '18 at 13:43
  • Oh ok thank you Phill @Phil – dedi wibisono Sep 16 '18 at 14:03
  • @Phil Well, we could also use `require()` in template! The way you suggested will be compiled into `require()` anyway! – Axel Sep 17 '18 at 03:49

1 Answers1

16

You can use require()

For example:

<img v-for="image in images" :src="require(image.url)">
Axel
  • 4,365
  • 11
  • 63
  • 122