How to check if image is loaded in Vue/Nuxt?

Viewed 3820

New to Vue and Nuxt. I am trying to show skeletons before image is loaded completely.

Here's my attempt, skeleton shows but image is never loaded and onImageLoad is never called.

<template>
  <div>
    <img v-if="isLoaded" @load="onImgLoad" :src="me.img">
    <div v-else class="skeleton"></div>
  </div>
</template>

<script lang="ts">
export default {
  props: {
    me: Object,
  },
  data() {
    return {
      isLoaded: false,
    }
  },
  methods: {
    onImgLoad() {
      console.log(` >> isLoaded:`, this.isLoaded)
      return this.isLoaded = true
    },
  },
}
</script>

I have some broken image url to test fallback src, is it a problem? But I tried removing those broken links and it's still not working.

Example data:

export const me = {
  name: 'David',
  img: 'https//david.png', // Example broken > https://no.jpg
},

Please help me, what I am doing wrong?

1 Answers

Because isLoaded is false on the initial render, the img element is removed from the DOM tree. If it’s not in the DOM, the image src won’t be requested, ergo— no load event.

Switch to v-show. The img element will remain in the DOM, so the @load event will fire.

Related