英文:
Replace image with placeholder on src change
问题
我有一张带有绑定的src
值的图片
<img :src="image.url">
当image.url
更新时,旧图片会保留在原位,直到新图片加载完成。这可能会看起来有点奇怪,因为新图片在文本细节更改后仍然滞后。
如何在src
属性发生变化时使用vue.js替换图片为加载指示器?
我可以通过触发变化的代码添加DOM操作,这可以工作,但我宁愿使用vue绑定来正确处理。
英文:
I have an image with a bound src value
<img :src="image.url">
When image.url
gets updated, the old image stays in place until the new image is loaded. This can look a little weird as the new image lags behind the text details on change.
How can I replace the image with a loading indicator when the src
property changes with vue.js?
I could add DOM manipulation with the code that triggers the change and that works, but I'd rather do it properly with vue bindings.
答案1
得分: 4
- 在你的
data()
函数中添加一个imageLoading
属性。 - 将你的 :src 设置如下:
<img :src="imageLoading ? ./myPlaceholder.png : image.url" />
- 使用 $watch 来监视
image.url
的变化,以设置加载图像时的imageLoading
:
watch: {
'image.url': function() {
this.imageLoading = true;
}
- 在你的 img 标签中添加一个 @load 处理程序,以在图像加载完成时将
imageLoading
设置为 false:<img :src="imageLoading ? ./myPlaceholder.png : image.url" @load="imageLoading = false" />
关于 @load 处理程序的说明 - 从这个问题中大胆借鉴而来,该问题链接到一个示例。
英文:
This should get you on the right track:
- Have an
imageLoading
attribute in yourdata()
function. - Set your :src as follows:
<img :src="imageLoading ? ./myPlaceholder.png : image.url" />
- $watch your image.url to set the loading image whenever it changes:
watch: {
'image.url': function() {
this.imageLoading = true;
}
- Add an @load handler to your img tag to set imageLoading to false when the image loads:
<img :src="imageLoading ? ./myPlaceholder.png : image.url" @load="imageLoading = false" />
Note on the @load handler - shamelessly stolen from this question, which does link to an example.
答案2
得分: 0
这是一个基本的图像占位符组件,它使用插槽来显示任何占位符内容。
<template>
<div class="image">
<img :src="src" @load="ready = true" v-show="ready">
<slot v-if="!ready" />
</div>
</template>
<script>
export default {
props: ['src'],
data: () => ({
ready: false
}),
watch: {
src() { this.ready = false }
}
}
</script>
要使用它:
<image-placeholder src="IMAGE_URL">
<b>PLACEHOLDER CONTENT HERE</b>
<p>Can be anything</p>
<img src="ANOTHER_IMAGE_URL" />
</image-placeholder>
英文:
This is a basic image placeholder component that uses slots to display any placeholder content
<template>
<div class="image">
<img :src="src" @load="ready = true" v-show="ready">
<slot v-if="!ready" />
</div>
</template>
<script>
export default {
props: ['src'],
data: () => ({
ready: false
}),
watch: {
src () { this.ready = false }
}
}
</script>
to use it
<image-placeholder src="IMAGE_URL">
<b>PLACEHOLDER CONTENT HERE</b>
<p>Can be anything</p>
<img src="ANOTHER_IMAGE_URL" />
</image-placeholder>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论