Vue.js组件图像空白

问题描述:

我已经将一个计算属性绑定到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

*更新:只要内容以任何方式重新绘制,任何元素中的任何布局更改都会导致它呈现。这可能是一个好的开始。 –

的问题是图像配有风格'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属性有关。 –

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。