Vue.js v-for do no render image

84 views Asked by At

I'm trying to render four images using v-for with a range, 1 to 4. v-for="n in 4" :key"n" But, using 'n' as part of src does not work. Why?

 <div v-for="n in 4" :key="n">
    <img
       :src="`../assets/images/image-product-${n}-thumbnail.jpg`"
       class="rounded-xl h-16 w-16 hover:cursor-pointer"
    />
 </div>

Tried using 'key' instead of 'n', converting 'n' to string... none worked

If I hardcorde like this, it works

<img
      src="../assets/images/image-product-1-thumbnail.jpg"
      class="rounded-xl h-16 w-16 hover:cursor-pointer"
 />
2

There are 2 answers

0
Raphael Rlt On

If you have a global aliases (@) available i recommend you to use it.

Because using relative path can works in local for example but when the project is compile (build) the related path can be broken.

When using dynamic src path you can require it before loading.

With the aliases you can do:

:src="`require(@/assets/images/image-product-${n}-thumbnail.jpg`)"
1
Dalía Macias On

I had the same issue, but the problem is not the path or the @ in the path, I've tried this:

    <img class="product-listed" :src="`${product.src}`">

    <button @click="navigateTo(product.id)" class="add-to-cart">Añadir al carrito</button>
   <h4> {{product.name }}</h4>
   <p>{{ product.precio }}</p>
</div>

And in the browser DOM this is what I see:

If I place an image manually with the same path, it shows up, but when is inside a dinamically path (v-for) coming from the API, the image does not show up. By the way Im using Vue JS version Option API.

Also I've tried: :src="require(${product.src})" where the product.src is declared in the JSon (API) like following: { "name":"product1", "src":"../assets/img/product2.png", "precio":"15.50", "categoryID":1, "id": "1" },

And if I console log the product, it has the right path. and properties. It works on my local enviroment, maybe it could help you