在Vue.js中加载图像时显示旋转器

4
在以下示例中,我使用Vue.js制作了一个简单的图像旋转器加载程序:

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

问题在于,特别是对于较大的图片,图片经常会逐块加载。这对用户来说不太美观。

输入图像说明


只有当图片完全加载完毕时才应该显示图片。在图片没有完全加载之前,应该显示旋转器。

我可以怎么做才能让它起作用?

2个回答

8
标签会发出一个事件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>


0

Using 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"

工作演示


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接