Shodan4004
Shodan4004

Reputation: 57

Vue.js dynamic images not working in v-for

im trying to display some images inside a v-for putting the results in the img src=""

<div v-for="piatto in portata" class="card mb-3">
        <div class="row">
          <div class="col-lg-4">
            <img src="'/img/food/' + piatto.img_id + '.jpg'" alt="" style="height:;" class="img-fluid rounded-start img-thumbnail" >
          </div>
          <div class="col-lg-8">
              <div class="card-body mt-3">
                <h3 class="card-title">{{piatto.food_name}}</h3>
                <h4 class="card-text text-primary">{{piatto.price}}€</h4>
                <button type="button" @click="sendOrder(piatto.food_name)" class="btn btn-dark">Aggiungi</button>
              </div>
          </div>
        </div> 
      </div>

The <img src="'/img/food/' + piatto.img_id + '.jpg'" syntax doesnt seem to work. I dunno if im doing some error in the syntax, or maybe this way of solving the problem is just not viable. Im pretty new to vue. Thanks in advance

Upvotes: 2

Views: 58

Answers (1)

kissu
kissu

Reputation: 46594

If you are using Webpack

If the images are hosted somewhere on the Internet, you can do that

<template>
  <section style="display: flex">
    <div v-for="element in elements" :key="element.id" class="">
      <img :src="`${imageInitialUrl}${element.imageId}`" />
      <p>{{ element.name }}</p>
    </div>
  </section>
</template>

<script>
export default {
  data() {
    return {
      imageInitialUrl: 'https://source.unsplash.com/random/200x200?sig=',
      elements: [
        {
          id: 1,
          name: 'bob',
          imageId: '1',
        },
        {
          id: 2,
          name: 'patrick',
          imageId: '2',
        },
        {
          id: 3,
          name: 'sarah',
          imageId: '3',
        },
      ],
    }
  },
}
</script>

This is how it will look.

enter image description here


This is how its written if the images are local

<img :src="require(`@/assets/images/${element.imageId}.jpg`)" />

With this kind of structure

enter image description here

Upvotes: 3

Related Questions