Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show spinner while loading image in Vue.js

In the following example I made a simple image spinner loader with Vue.js:

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.

enter image description here


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?

like image 953
Tenarius Avatar asked Sep 05 '25 16:09

Tenarius


1 Answers

The image will be emitting an event load which will be fired once the image is loaded.

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>
like image 126
Stark Buttowski Avatar answered Sep 07 '25 17:09

Stark Buttowski