簡體   English   中英

如何將圖像 src 屬性綁定到動態值

[英]How to bind an image src attribute to a dynamic value

我是 vue.js 的初學者。 我創建了一個 Vue 組件“卡片”,其中包含一些 Vue 組件“卡片”。 我在:src="{ card.imgSource }"中有一個錯誤。 我不知道我該怎么做才能解決它。 請幫我。

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 : ''
      }
    },

  });

將其更改為:src="card.imageSource"

使用:src="{ card.imageSource }"您基本上嘗試傳遞帶有格式錯誤的 object 屬性的 object 文字。

假設您的imageSource'http://example.com/img.jpg' ,您實際上將 object { 'http://example.com/img.jpg' }作為src傳遞,這不是有效的 object (也不是有效的圖像 URL)

要理解我說您傳遞 object 文字時的意思,請嘗試這樣做: :src="{ key: card.imageSource }"並檢查 DOM。 您的錯誤將消失,您很可能會看到src="[object Object]"

如果仍然有點難以理解,請嘗試閱讀 Vue.js 文檔中的插值部分,它會對您有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM