Allow placeholder override

Allow overriding the default placeholder icon, and add error handling to fallback to placeholder icon if the specified `img` cannot be loaded.
This commit is contained in:
Jim Kriz
2023-04-04 16:22:40 -04:00
parent f34c086960
commit 5eced3229b
3 changed files with 55 additions and 4 deletions

View File

@@ -1,21 +1,30 @@
<template>
<div class="relative">
<div v-if="!img" :class="avatarPlaceholderWrapperClasses">
<svg v-if="!initials" :class="avatarPlaceholderClasses" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg">
<img v-if="img && !imageError" :class="avatarClasses" :src="img" :alt="alt" @error="setImageError">
<div v-else :class="avatarPlaceholderWrapperClasses">
<svg v-if="!initials && !hasPlaceholder" :class="avatarPlaceholderClasses" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" d="M10 9a3 3 0 100-6 3 3 0 000 6zm-7 9a7 7 0 1114 0H3z" clip-rule="evenodd"></path>
</svg>
<slot v-else-if="!initials && hasPlaceholder" name="placeholder" />
<div v-else :class="avatarPlaceholderInitialsClasses">{{ initials }}</div>
</div>
<img v-else :class="avatarClasses" :src="img" :alt="alt">
<span v-if="status" :class="avatarDotClasses" :data-pos="statusPosition"></span>
</div>
</template>
<script lang="ts" setup>
import { toRefs } from 'vue'
import { computed, ref, toRefs, useSlots } from 'vue'
import type { PropType } from 'vue'
import type { AvatarSize, AvatarStatus, AvatarStatusPosition } from './types'
import { useAvatarClasses } from '@/components/Avatar/composables/useAvatarClasses'
const imageError = ref(false)
function setImageError() {
imageError.value = true
}
const slots = useSlots()
const hasPlaceholder = computed(() => slots.placeholder)
const props = defineProps({
alt: {
type: String,
@@ -53,6 +62,10 @@ const props = defineProps({
type: String,
default: null,
},
placeholder: {
type: Object,
default: null,
},
})
const { avatarClasses, avatarDotClasses, avatarPlaceholderClasses, avatarPlaceholderWrapperClasses, avatarPlaceholderInitialsClasses } = useAvatarClasses(toRefs(props))