Skip to content

Commit

Permalink
feat: support load event for nuxt-img and nuxt-picture (nuxt#702)
Browse files Browse the repository at this point in the history
  • Loading branch information
piscis authored Jan 23, 2023
1 parent 61bc66f commit 60cd126
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 4 deletions.
12 changes: 9 additions & 3 deletions src/runtime/components/nuxt-img.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -94,15 +95,20 @@ export default defineComponent({
appendHeader(useRequestEvent(), 'X-Nitro-Prerender', sources.join(','))
}

const imgEl = ref<HTMLImageElement>(null)
const imgEl = ref<HTMLImageElement>()

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)
}
}
})
Expand Down
12 changes: 11 additions & 1 deletion src/runtime/components/nuxt-picture.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand All @@ -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)
Expand Down Expand Up @@ -69,6 +70,14 @@ export default defineComponent({
}
}

const imgEl = ref<HTMLImageElement>()

onMounted(() => {
imgEl.value!.onload = (event) => {
ctx.emit('load', event)
}
})

return () => h('picture', { key: nSources.value[0].src }, [
...(nSources.value?.[1]
? [h('source', {
Expand All @@ -78,6 +87,7 @@ export default defineComponent({
})]
: []),
h('img', {
ref: imgEl,
..._base.attrs.value,
...imgAttrs,
src: nSources.value[0].src,
Expand Down

0 comments on commit 60cd126

Please sign in to comment.