最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to check if image is loaded in VueNuxt? - Stack Overflow

programmeradmin0浏览0评论

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

What I am doing wrong?

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?

Share Improve this question edited May 28, 2023 at 10:33 halfer 20.4k19 gold badges108 silver badges201 bronze badges asked Dec 4, 2020 at 16:24 SwixSwix 2,11311 gold badges38 silver badges57 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 18

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.

发布评论

评论列表(0)

  1. 暂无评论