2

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.

kissu
  • 40,416
  • 14
  • 65
  • 133
mikeym
  • 5,705
  • 8
  • 42
  • 62
  • have you defined `items` in *data* ? – Saeed Apr 19 '22 at 04:13
  • @Saeed yes, `items` is defined on data also. I forgot to mention that the other values of each item in the `v-for` display perfectly fine, so there is no problem there. It is simply that the `img` element is not displaying the images despite the fact that the correct paths are in the HTML. – mikeym Apr 19 '22 at 04:18
  • `taking up the appropriate space`, did you check width and height of images? any *overflow hidden* style or something like that? – Saeed Apr 19 '22 at 04:24
  • @Saeed there is an overflow hidden on the div wrapping the img tag. The height and width on the img tag itself are 100%. I just tried pasting in a url using the dev console and it immediately showed on the page, so I think the CSS is fine. – mikeym Apr 19 '22 at 04:39
  • Does this answer your question? [Vue.js dynamic images not working](https://stackoverflow.com/questions/40491506/vue-js-dynamic-images-not-working) – Kapcash Apr 19 '22 at 07:22
  • Yep, you're probably looking at the wrong place here. As @Kapcash proposed, a `require` should do the trick when it comes down to dynamic stuff. Here is the part in [the documentation](https://nuxtjs.org/docs/directory-structure/assets#images) related to Nuxt images. – kissu Apr 19 '22 at 08:40
  • due to the nature of the beast, rather than needing to rebuild your app every time you add a new item, look into storing non-design related files and images on the server's filesystem or s3 etc – Lawrence Cherone Apr 19 '22 at 16:42

3 Answers3

6

in Nuxt v3, you can use it like so

<script setup>
import img1 from `~/path/to/img1`
</script>

<template>
  <img :src="img1" />
</template>
kissu
  • 40,416
  • 14
  • 65
  • 133
Liviu
  • 241
  • 3
  • 5
  • 1
    How can you get this to work with dynamic images in Nuxt 3? – Leggy Sep 24 '22 at 12:36
  • 3
    Just import all images that you may need dynamically. you may place them in an object or array. If you have a ton of images and is not doable for you, most probably must move your images on a CDN and get full URLs from there. Another option would be to place your images in the `public/` folder. I would also like to know if there's a better way to dynamically import assets in Nuxt 3. Will come up with an update if I find out. – Liviu Sep 25 '22 at 16:00
2

Try to use it this way

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

As shown in the Nuxt documentation regarding the images.

kissu
  • 40,416
  • 14
  • 65
  • 133
  • 2
    Please note that this solution does not work in Nuxt 3, it will only work in Nuxt 2 – Maurice Jan 08 '23 at 02:20
  • 1
    @Maurice rectification, this only works with Webpack, not with Vite. Nuxt3 can be used with Webpack5. – kissu Jan 08 '23 at 04:18
  • 1
    good callout. I guess by default, the Nuxt3 project generator configures new projects with Vite, which is why this option didn't work for me. Also worth noting is that there is an issue open on GH around better handling for this situation: https://github.com/nuxt/framework/issues/7121 – Maurice Jan 09 '23 at 05:12
0

Worinkg with Nuxt 3 and import img1 from ~/path/to/img1 works fine but I've had an error while working with typescript. I think in Nuxt 2 dynamic :src attributes was working better :).

Anyway if you like to play with typescript and don't want to have an errors see my approach below. $slugify is just an extra plugin I needed to convert attribute to right image name.

Stack:

  • Nuxt 3 with typescript (docs)
  • Tailwind

plugins/slugify.ts

export default defineNuxtPlugin(() => {
  return {
    provide: {
      slugify: (text: string) => {       
        return `${
          text
            .toLocaleLowerCase()
            .trim()
            .replace(/[^\w\s-]/g, '')
            .replace(/[\s_-]+/g, '-')
            .replace(/^-+|-+$/g, '')
          }`
      }
    }
  }
})
// "Any String" will be converted to "any-string"

components/ImageComponent.vue

<script setup lang="ts">
const props = defineProps({
    imageSrc: {
      type: String,
      required: true,
    }
})
</script>

<template>
  <div
    :class="`bg-[url('${props.imageSrc)}')]`"
  >
  <div>
</template>

Usage

<template>
  <div>
    <h1>My awesome image.png</h1>
    <ImageComponent
      class="w-16 h-16 bg-contain"
     :image-src="`${$slugify('My awesome image.png')}`"
    />
  </div>
</template?

my-awesome-image.png must be placed in public folder


Another way - the easiest one!!!

You can also use Nuxt Image where you can pass image :src in a dynamic way :)

Michael Stachura
  • 1,100
  • 13
  • 18