简体   繁体   中英

How to bind an image src attribute to a dynamic value

I'm a beginner in vue.js. I've create a Vue component "cards" that has some Vue componet "card". I have an error in :src="{ card.imgSource }" . I don't know what should I do to solve it. Please help me.

Vue.component('cards' , {
    props: ['cards'],
    template : `
    <div class="row products">
            <card v-for="(card , index) in cards" :card="card" :index="index"></card>
    </div>
    `
  });


  Vue.component('card' , {
    props :['card' , 'index'],
    template : `
        <div class="col-md-4 product">
        <div class="card">
            <img :src="{ card.imgSource }" class="card-img-top" alt="...">
            <div class="card-body">
                <h5 class="card-title">{{ card.title }}</h5>
                <p class="card-text">{{ card.body }}</p>
                <a href="#" class="btn btn-primary">Go somewhere</a>
            </div>
        </div>
            
        </div>
    `
  });


  let imgs = "img/shoe_img.jpg";

  let app = new Vue({
    el : '#app',
    data : {
      cards : [
        { title : 'Product 1' , body : "Some quick example text to build on the card title and make up the bulk of the card's content." ,imgSource : imgs },
        { title : 'Product 2' , body : "Some quick example text to build on the card title and make up the bulk of the card's content." ,imgSource: imgs},
        { title : 'Product 3' , body : "Some quick example text to build on the card title and make up the bulk of the card's content." ,imgSource: imgs}
      ],
      alert : {
        title : '',
        message : '',
        show : false ,
        type : ''
      }
    },

  });

Change it for :src="card.imageSource" .

With the :src="{ card.imageSource }" you basically try to pass an object literal with a malformed object property.

Assuming your imageSource is 'http://example.com/img.jpg' you are effectively passing as a src the object { 'http://example.com/img.jpg' } which is not a valid object (nor a valid image URL) .

To understand what I mean when I say you are passing an object literal, try doing that: :src="{ key: card.imageSource }" and inspect the DOM. Your error will disappear, and you will most likely see src="[object Object]" .

If it's still a bit hard to understand, try reading the section on interpolations in the Vue.js documentation, it will help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM