Vuejs 2: how to define the img.complete property

I have code that retrieves a list of images as an object, e.g.

[
  { src: '/path/to/img.jpg', loaded: false },
  ...
]

and a template that then displays them as HTML, for example:

<div
  v-for="image in alltheimages"
  :key="image.id" >
  <transition name="fade" appear>
  <img
    :src="image.src"
    v-show="image.loaded"
    @load="image.loaded = true"
    />
  </transition>
</div>

This works well on the first page load; images disappear as soon as they are loaded.

However, a problem arises when the image is already loaded into the cache , because then it @loadnever works on a new element <img>. In these situations, I can check the DOM img tag property .complete, but how can I do this in VueJS?

I tried v-show="this.complete || image.loaded", but thisjust points to window. I thought I could use a method call and pass a reference to the element that initiated the call, but I cannot find out how to do this.

, new Image(), listenter load, src, , , , - DOM, Vue.

+8
4

.

<div
  v-for="image in alltheimages"
  :key="image.id" >
  <transition name="fade" appear>
  <img
    :src="image.src"
    v-show="image.loaded"
    v-loadedifcomplete="image"
    @load="image.loaded = true"
    />
  </transition>
</div>

.

new Vue({
  ...
  directives: {
    loadedifcomplete: function(el, binding) {
       if (el.complete) {
         binding.value.loaded = true;
       }
    }
  }
  ...
});
+3

, vue-images -loaded, vue-onload .

main.js :

import OnLoad from 'vue-onload'
Vue.use(OnLoad);

:

<img 
  class="gallery__image" 
  v-onload="[image src]"
/>

CSS :

 /*loaded state*/
.gallery__image {
  opacity: 1;
  transition: opacity 1s linear;
}

 /*unloaded state*/
.gallery__image[data-src]{
  opacity: 0;
}
0

You can bind to your own event onLoadand call any method in your component that you want. demonstration

<div id="app">
    <img v-for="num in [1,2,3,4]"
         src="http://lorempixel.com/400/200"
         :onLoad="onLoadHandler()" />
</div>


new Vue({
    el: '#app',
    methods: {
        onLoadHandler: function() {
            alert('hi');
        }
    }
});
-1
source

All Articles