PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, October 17, 2022

[FIXED] How to use dynamic images in Nuxt?

 October 17, 2022     javascript, nuxt.js, vue.js     No comments   

Issue

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 class="item-img">
   <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.


Solution

Try to use it this way

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

As shown in the Nuxt documentation regarding the images.



Answered By - kissu
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing