Home > Back-end >  How to use dynamic images in Nuxt?
How to use dynamic images in Nuxt?

Time:04-20

I am trying to display images from an assets folder in a Nuxt but it won't work even if the src value in the HTML is correct.

Here is an excerpt of the code.

<div v-for="(item, index) in items" :key="index">
  <div >
   <img :src="`../assets/imgs/${item.img}`"/>
  </div>
</div>

The above path is correct as the component is inside a pages folder at the same root level as the assets folder.

I have image filenames in an array like so:

data() {
  return {
    images: ['image0.jpg', 'image1.jpg'],
  ...
}

There is an async function that is making an API call to fetch some items. When the API is finished a random image is added to each item.

async getMovies() {
  const data = axios.get `api_call_here`)
  const result = await data
  result.data.results.forEach((item) => {
    let randomImg = 
    this.images[Math.floor(Math.random() * 
    this.images.length)]
    item.img = randomImg
    this.items.push(item)
  })
},

I am sure the path to the images is correct and that they exist in the specified folder. I also know the path works because I can display any single image from the same assets folder inside another component at the same level.

I think I have tried every combination for the interpolation inside the src attribute and nothing has worked.

Lastly, I can see the correct path in the elements themselves when I inspect them in the developer console. What is even more baffling is the images seem to be taking up the appropriate space on the page but they are empty (blank space).

I have run out of ideas. If anyone can help me figure out what is going wrong I'd be very grateful.

CodePudding user response:

Try to use it this way

<img :src="require(`../assets/imgs/${item.img}`)" />

As shown in the Nuxt documentation regarding the images.

  • Related