1
0
Fork 1
mirror of https://github.com/elk-zone/elk.git synced 2024-11-05 08:29:57 +00:00
elk/components/common/CommonBlurhash.vue

55 lines
1,023 B
Vue
Raw Normal View History

<script setup lang="ts">
import { decode } from 'blurhash'
2023-02-15 10:34:23 +00:00
const { blurhash, src, srcset, shouldLoadImage = true } = defineProps<{
2023-01-05 16:48:20 +00:00
blurhash?: string | null | undefined
src: string
srcset?: string
2023-02-15 10:34:23 +00:00
shouldLoadImage?: boolean
}>()
defineOptions({
inheritAttrs: false,
})
const isLoaded = ref(false)
2023-01-05 16:48:20 +00:00
const placeholderSrc = $computed(() => {
if (!blurhash)
return ''
const pixels = decode(blurhash, 32, 32)
return getDataUrlFromArr(pixels, 32, 32)
})
2023-02-15 10:34:23 +00:00
function loadImage() {
const img = document.createElement('img')
img.onload = () => {
isLoaded.value = true
}
img.src = src
if (srcset)
img.srcset = srcset
setTimeout(() => {
isLoaded.value = true
}, 3_000)
2023-02-15 10:34:23 +00:00
}
onMounted(() => {
if (shouldLoadImage)
loadImage()
})
watch(() => shouldLoadImage, () => {
if (shouldLoadImage)
loadImage()
})
</script>
<template>
<img v-if="isLoaded || !placeholderSrc" v-bind="$attrs" :src="src" :srcset="srcset">
<img v-else v-bind="$attrs" :src="placeholderSrc">
</template>