Search code examples
vue.jsfor-loopfor-in-loop

How to get the Images to display using v-for?


I used v-for on an array (named items) which contains name and url of respective images but when i give the image URL of an individual to the img tag it shows nothing.

This is code to display Images

    <template>
    <main>
      <div v-bind:key="item" v-for="item in items">
        <img src=item.url alt="No Image" title="Order Now" />
        <section>{{item.name}}</section>
      </div>
    </main>
    </template>

    <script>
    export default {
    name: 'ShowCase',
    data() {
      return{
        items:[
          {
            name:"Doritos Nacho Cheese", 
            url:"../assets/dnc.jpg"
          },
          {
            name:"Kurkure Hyderbadi Hungama", 
            url:"../assets/kkhh.jpg"
          }, 
        ]
      }
    }

![**check this image (image doesn't show up in webpage)][2]


Solution

  • Currently, you're not using VueJS binding to tell your images their src, so instead of a URL, they receive the string item.url

    Just replace

    <img src="item.url" alt="No Image" title="Order Now" />
    

    With

    <img :src="item.url" alt="No Image" title="Order Now" />
    

    And it should work. The : (alias of v-bind:) before src tells VueJS it's a dynamic attribute and it must look for its value into the component context.

    N.B: Don't forget the double quotes around item.url, they're mandatory.