1

I have created an Array with three objects and a loop over it in my template. It is working fine for getting other data and src data but it is not showing my images. Does anybody what should i do?

sandbox link to my project

And here is my template code

<div
  class="box m-3"
  @click="selectBox(item.id)"
  v-for="item in boxData"
  :key="item.id"
  :class="{
    'border-select': selected(item.id),
  }"
>
  <p>{{ item.name }}</p>
  <img :src="item.src" width="60" alt="" />
  src: {{item.src}}
</div>

My data

boxData: [
    { id: 1, name: "object 1", src: "@/assets/power(1).png" },
    { id: 2, name: "object 2", src: "@/assets/power(1).png" },
    { id: 3, name: "object 3", src: "@/assets/power(1).png" },
  ],
marjan
  • 97
  • 7
  • 1
    Does this answer your question? [How to use dynamic images in Nuxt?](https://stackoverflow.com/questions/71919492/how-to-use-dynamic-images-in-nuxt) – kissu Apr 27 '22 at 07:15

3 Answers3

5

Solution 1: If you don't want to use Webpack assets from the assets directory, you can add the images to the static directory.

In your code, you can then reference these files relative to the root (/):

<!-- Static image from static directory -->
<img src="/my-image.png" />

<!-- webpacked image from assets directory -->
<img src="~/assets/my-image-2.png" />

Nuxt doesn't change this path, so if you customize your router.base then you'll need to make sure to add that manually to your paths. For example:

<img :src="`${yourPrefix}/my-image.png`" />

Solution 2: When working with dynamic images you will need to use require

 <img :src="require(`~/assets/img/${image}.jpg`)" />

Image not displaying in loop Vue.js

Ali Raza
  • 670
  • 5
  • 15
0
<img :src="require(`@/assets/${item.src}`)" width="60" alt="" /> src: {{ item.src }}

It worked like this

marjan
  • 97
  • 7
0

Another possible reason could be that the @ alias is not correctly configured in your project. You can try replacing @ with the actual path to the src directory, for example:

 <img :src="`./src/assets/img/${image}.jpg`" />
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jul 02 '23 at 05:28