Search code examples
javascriptimagevue.jssrc

Vue 3 dynamic image


I am using a v-for to load data on cards. The image is not showing up and not sure why. I though :src = "'item.img'" or :src = "{{item.img}}" would work, but neither are working.

Here is my code

 <div v-for="(item, index) in basicData" :key="index">
      <transition class="slide">
        <div v-if="index >= start && index < end" class="card">
          <div class="card-body">
            <h5 class="card-title">{{item.title}}</h5>
            <img
              :src="'item.img'"
              class="card-img-top"
              :alt="'item.img'"
              style="margin: 20px 5px"
            />
            <p class="card-text">Some quick example text.</p>
          </div>
        </div>
      </transition>

and here is the screen shot

enter image description here

When I hard code src="../assets/featured/pizzaOne.jpeg" the image appears.


Solution

  • You can create method or computed property:

    methods() {
      getImage(imagePath) {
        return require(imagePath);
      }
    }
    

    Then in template call that method:

    <img
      :src="getImage(item.img)"
      class="card-img-top"
      :alt="item.img"
      style="margin: 20px 5px"
    />