2017-07-28 104 views
0

我已經將一個計算屬性綁定到Vue.js中圖像標記的src。該代碼似乎是正確的,但並不一致,這對我來說是莫名其妙的。此外,切換到​​頁面並返回到主要圖書頁面始終正確顯示圖像。Vue.js組件圖像空白

任何有關可能導致此問題的信息都會很棒!

甲託管該應用的版本是可用這裏:https://books.surge.sh/

The relevant code for the book-item component.

The full Github repo.

的碼生成的書分量和圖像src如下:

<template> 
    <article class="book-item"> 
    <img :src="imgSrc" class="image"> 
    <div class="meta"> 
     <div class="name">{{ book.title }}</div>* 
     <div class="author">{{ book.author }}</div> 
    </div> 
    <div class="description"> 
     <p v-html="book.description"></p> 
    </div> 
    </article> 
</template> 

<script> 
export default { 
    props: ['book'], 
    computed: { 
    imgSrc() { 
     return `/static/img/${this.book.image}`; 
    } 
    } 
}; 
</script> 

部分在初始加載時顯示書籍封面:

Partially displayed images.

+0

看起來像你的CSS問題,因爲如果你打開鉻devtools,並檢查元素,你總是可以看到src標籤,並正確鏈接。當我簡單地將你的'img'設置爲'display:block'時,它已經觸發並渲染它。 –

+0

*更新:只要內容以任何方式重新繪製,任何元素中的任何佈局更改都會導致它呈現。這可能是一個好的開始。 –

回答

1

的問題是圖像配有風格'width'。您應該在組件呈現後指定.image類。這樣做:

<template> 
 
    <article class="book-item"> 
 
    <img :src="imgSrc" :class="{image: componentLoaded}"> <!-- 1. change class --> 
 
    <div class="meta"> 
 
     <div class="name">{{ book.title }}</div>* 
 
     <div class="author">{{ book.author }}</div> 
 
    </div> 
 
    <div class="description"> 
 
     <p v-html="book.description"></p> 
 
    </div> 
 
    </article> 
 
</template> 
 

 
<script> 
 
export default { 
 
    props: ['book'], 
 
    data() { 
 
    return { 
 
     componentLoaded: false   // 2. add this 'state' data 
 
    }; 
 
    }, 
 
    computed: { 
 
    imgSrc() { 
 
     return `/static/img/${this.book.image}`; 
 
    } 
 
    }, 
 
    mounted() { 
 
    // 3. This will assign class to your image 
 
    // after component did mounted (nextTick() did not helped) 
 
    setTimeout(() => { 
 
     this.componentLoaded = true; 
 
    }, 1); 
 
    } 
 
}; 
 
</script>

祝你好運! 我創建了一個拉請求here

+0

非常感謝您的幫助!我找到了一種方法讓它只處理CSS更改,但是它意識到這個問題與圖像的高度/寬度CSS屬性有關。 –

0

As @ Stephan-v指出,問題出在img高度和寬度的CSS屬性。 .image類已被設置爲width: 150px; height: 100%;,但由於圖像src在Vue的生命週期掛鉤完成之前未設置,所以CSS無法正確應用,直到強制重新呈現爲止,例如切換出路由並返回。

我解決了這個由各地img像這樣創建容器div

<div class="image-container"> 
    <img :src="'/static/img/' + image" class="image"> 
</div> 

然後使用min-heightmin-width設置容器的大小,只有孩子imgwidth屬性設置爲一個硬值:

> .image-container { 
    min-width: 150px; 
    min-height: 100%; 

    img { width: 150px; } 
} 

這樣做可以防止任何「動態」CSS值(百分比寬度或高度規則)應用於具有動態設置src。