forked from Mirrors/elk
refactor: convert CommonBlurhash to Vue SFC file (#795)
Co-authored-by: 三咲智子 <sxzz@sxzz.moe>
This commit is contained in:
parent
f177ea1ea8
commit
31ee71c0d1
2 changed files with 43 additions and 45 deletions
|
@ -1,45 +0,0 @@
|
|||
import { decode } from 'blurhash'
|
||||
|
||||
export default defineComponent({
|
||||
inheritAttrs: false,
|
||||
props: {
|
||||
blurhash: {
|
||||
type: String,
|
||||
required: true,
|
||||
},
|
||||
src: {
|
||||
type: String,
|
||||
required: true,
|
||||
},
|
||||
srcset: {
|
||||
type: String,
|
||||
required: false,
|
||||
},
|
||||
},
|
||||
setup(props, { attrs }) {
|
||||
const placeholderSrc = ref<string>()
|
||||
const isLoaded = ref(false)
|
||||
|
||||
onMounted(() => {
|
||||
const img = document.createElement('img')
|
||||
img.onload = () => {
|
||||
isLoaded.value = true
|
||||
}
|
||||
img.src = props.src
|
||||
if (props.srcset)
|
||||
img.srcset = props.srcset
|
||||
setTimeout(() => {
|
||||
isLoaded.value = true
|
||||
}, 3_000)
|
||||
|
||||
if (props.blurhash) {
|
||||
const pixels = decode(props.blurhash, 32, 32)
|
||||
placeholderSrc.value = getDataUrlFromArr(pixels, 32, 32)
|
||||
}
|
||||
})
|
||||
|
||||
return () => isLoaded.value || !placeholderSrc.value
|
||||
? h('img', { ...attrs, src: props.src, srcset: props.srcset })
|
||||
: h('img', { ...attrs, src: placeholderSrc.value })
|
||||
},
|
||||
})
|
43
components/common/CommonBlurhash.vue
Normal file
43
components/common/CommonBlurhash.vue
Normal file
|
@ -0,0 +1,43 @@
|
|||
<script setup lang="ts">
|
||||
import { decode } from 'blurhash'
|
||||
|
||||
const { blurhash, src, srcset } = defineProps<{
|
||||
blurhash: string
|
||||
src: string
|
||||
srcset?: string
|
||||
}>()
|
||||
|
||||
defineOptions({
|
||||
inheritAttrs: false,
|
||||
})
|
||||
|
||||
const placeholderSrc = ref<string>()
|
||||
const isLoaded = ref(false)
|
||||
|
||||
onMounted(() => {
|
||||
const img = document.createElement('img')
|
||||
|
||||
img.onload = () => {
|
||||
isLoaded.value = true
|
||||
}
|
||||
|
||||
img.src = src
|
||||
|
||||
if (srcset)
|
||||
img.srcset = srcset
|
||||
|
||||
setTimeout(() => {
|
||||
isLoaded.value = true
|
||||
}, 3_000)
|
||||
|
||||
if (blurhash) {
|
||||
const pixels = decode(blurhash, 32, 32)
|
||||
placeholderSrc.value = getDataUrlFromArr(pixels, 32, 32)
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<img v-if="isLoaded || !placeholderSrc" v-bind="$attrs" :src="src" :srcset="srcset">
|
||||
<img v-else v-bind="$attrs" :src="placeholderSrc">
|
||||
</template>
|
Loading…
Reference in a new issue