From 60cd126a6f676fede44af5902230737591141443 Mon Sep 17 00:00:00 2001 From: Alex Date: Mon, 23 Jan 2023 12:03:40 +0100 Subject: [PATCH] feat: support `load` event for `nuxt-img` and `nuxt-picture` (#702) --- src/runtime/components/nuxt-img.ts | 12 +++++++++--- src/runtime/components/nuxt-picture.ts | 12 +++++++++++- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/src/runtime/components/nuxt-img.ts b/src/runtime/components/nuxt-img.ts index 4d8bf0cdd..2e9f8da6f 100644 --- a/src/runtime/components/nuxt-img.ts +++ b/src/runtime/components/nuxt-img.ts @@ -13,6 +13,7 @@ export const imgProps = { export default defineComponent({ name: 'NuxtImg', props: imgProps, + emits: ['load'], setup: (props, ctx) => { const $img = useImage() const _base = useBaseImage(props) @@ -94,15 +95,20 @@ export default defineComponent({ appendHeader(useRequestEvent(), 'X-Nitro-Prerender', sources.join(',')) } - const imgEl = ref(null) + const imgEl = ref() onMounted(() => { if (placeholder.value) { const img = new Image() img.src = mainSrc.value - img.onload = () => { - imgEl.value.src = mainSrc.value + img.onload = (event) => { + imgEl.value!.src = mainSrc.value placeholderLoaded.value = true + ctx.emit('load', event) + } + } else { + imgEl.value!.onload = (event) => { + ctx.emit('load', event) } } }) diff --git a/src/runtime/components/nuxt-picture.ts b/src/runtime/components/nuxt-picture.ts index 3be648c20..c6582e827 100644 --- a/src/runtime/components/nuxt-picture.ts +++ b/src/runtime/components/nuxt-picture.ts @@ -1,4 +1,4 @@ -import { h, defineComponent, computed } from 'vue' +import { h, defineComponent, ref, computed, onMounted } from 'vue' import { useBaseImage, baseImageProps } from './_base' import { useImage, useHead } from '#imports' import { getFileExtension } from '#image' @@ -12,6 +12,7 @@ export const pictureProps = { export default defineComponent({ name: 'NuxtPicture', props: pictureProps, + emits: ['load'], setup: (props, ctx) => { const $img = useImage() const _base = useBaseImage(props) @@ -69,6 +70,14 @@ export default defineComponent({ } } + const imgEl = ref() + + onMounted(() => { + imgEl.value!.onload = (event) => { + ctx.emit('load', event) + } + }) + return () => h('picture', { key: nSources.value[0].src }, [ ...(nSources.value?.[1] ? [h('source', { @@ -78,6 +87,7 @@ export default defineComponent({ })] : []), h('img', { + ref: imgEl, ..._base.attrs.value, ...imgAttrs, src: nSources.value[0].src,