简体   繁体   English

在 Vue.js 中加载图像时显示微调器

[英]Show spinner while loading image in Vue.js

In the following example I made a simple image spinner loader with Vue.js :在以下示例中,我使用Vue.js制作了一个简单的图像微调器加载器:

https:// jsfiddle.net/Tenarius/g2chd796/8/ https://jsfiddle.net/Tenarius/g2chd796/8/

The problem is that, especially with larger images, the image often loads piece by piece .问题是,尤其是对于较大的图像,图像通常会一块一块地加载。 That doesn't look good to the user.这对用户来说并不好。

在此处输入图像描述


The picture should only be displayed when it is fully loaded.图片应仅在完全加载时显示。 As long as the image is not fully loaded, the spinner should be displayed.只要图像未完全加载,就应该显示微调器。

What can I do to make it work?我该怎么做才能让它发挥作用?

The image will be emitting an event load which will be fired once the image is loaded.图像将发出一个事件load ,一旦加载图像就会触发该事件。

 new Vue({ el: "#app", data: { imgsrc: "", btntext: "Show Image", isLoaded: false, isLoading: false }, methods: { loaded() { this.isLoaded = true; this.isLoading = false; }, toggleimg: function(){ if (this.imgsrc == "") { this.isLoaded = false; this.isLoading = true; this.imgsrc = "https://images2.alphacoders.com/103/1039991.jpg" this.btntext = "Hide Image" }else{ this.imgsrc = "" this.btntext = "Show Image" } } } })
 .loading { background: transparent url('https://miro.medium.com/max/882/1*9EBHIOzhE1XfMYoKz1JcsQ.gif') center no-repeat; height: 400px; width: 400px; }
 <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <div id="app"> <h2>Image Loader Spinner</h2> <button @click="toggleimg">{{ btntext }}</button> <div v-if="isLoading" class="loading"></div> <img v-show="isLoaded":src="imgsrc" width="400" @load="loaded"> </div>

Using new Image()使用new Image()

var myImage = new Image();
myImage.src = 'https://images2.alphacoders.com/103/1039991.jpg';
myImage.onload = () => {
    this.imgsrc = myImage.src
}      
this.imgsrc = 'https://miro.medium.com/max/882/1*9EBHIOzhE1XfMYoKz1JcsQ.gif'
this.btntext = "Hide Image"

Working Demo工作演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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