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

6
  • 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? Commented Sep 16, 2018 at 10:44
  • Are you using vue-cli? If so, which version? Commented Sep 16, 2018 at 13:21
  • yes, I using vue-cli 2.9.6 Commented Sep 16, 2018 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 ~ stackoverflow.com/questions/47313165/… Commented Sep 16, 2018 at 13:43
  • Oh ok thank you Phill @Phil Commented Sep 16, 2018 at 14:03

1 Answer 1

17

You can use require()

For example:

<img v-for="image in images" :src="require(image.url)">
Sign up to request clarification or add additional context in comments.

3 Comments

yes it works, thanks @Sanjay
What worked for me was wrap require in the JS like { url: require('../../assets/image1.png') }
it will be very useful to also mention why and how that does work.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.