在Vue.js中加载图片时显示微调框

时间:2020-07-07 14:26:01

标签: javascript image vue.js spinner loader

在以下示例中,我使用 Vue.js 创建了一个简单的图像微调器加载器:

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

问题在于,尤其是使用较大的图像时,图像通常会逐个加载 。对用户而言,这看起来不太好。

2


图片应仅在完全加载时显示。只要未完全加载图像,就应该显示微调器。

我该怎么做才能使其正常工作?

2 个答案:

答案 0 :(得分:2)

该图像将发出事件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>

答案 1 :(得分:0)

使用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"

Convert escaped Unicode character back to actual character