6

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
},

What I am doing wrong?

1 Answer 1

19

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.