mirror of
https://github.com/ArthurDanjou/ui.git
synced 2026-01-30 19:57:55 +01:00
fix: load icons on mount rather than within setup (#82)
This commit is contained in:
@@ -7,10 +7,9 @@
|
|||||||
|
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import type { IconifyIcon } from '@iconify/vue'
|
import type { IconifyIcon } from '@iconify/vue'
|
||||||
import { computed, ref, watch } from 'vue'
|
|
||||||
import { Icon as Iconify } from '@iconify/vue/dist/offline'
|
import { Icon as Iconify } from '@iconify/vue/dist/offline'
|
||||||
import { loadIcon } from '@iconify/vue'
|
import { loadIcon } from '@iconify/vue'
|
||||||
import { useNuxtApp, useState } from '#imports'
|
import { useNuxtApp, useState, computed, watch, onMounted } from '#imports'
|
||||||
|
|
||||||
const props = defineProps({
|
const props = defineProps({
|
||||||
name: {
|
name: {
|
||||||
@@ -20,19 +19,31 @@ const props = defineProps({
|
|||||||
})
|
})
|
||||||
const nuxtApp = useNuxtApp()
|
const nuxtApp = useNuxtApp()
|
||||||
const state = useState('u-icons', () => ({}))
|
const state = useState('u-icons', () => ({}))
|
||||||
const isFetching = ref(false)
|
|
||||||
const icon = computed<IconifyIcon | null>(() => state.value?.[props.name])
|
const isFetching = computed(() => !!state.value?.[props.name]?.then)
|
||||||
|
const icon = computed<IconifyIcon | null>(() => !state.value?.[props.name] || state.value[props.name].then ? null : state.value[props.name])
|
||||||
const component = computed(() => nuxtApp.vueApp.component(props.name))
|
const component = computed(() => nuxtApp.vueApp.component(props.name))
|
||||||
const loadIconComponent = async () => {
|
|
||||||
if (component.value) { return }
|
const loadIconComponent = (name: string) => {
|
||||||
if (!state.value?.[props.name]) {
|
state.value = state.value || {}
|
||||||
isFetching.value = true
|
if (nuxtApp.vueApp.component(props.name) || state.value[name] || state.value[name] === null) { return }
|
||||||
state.value[props.name] = await loadIcon(props.name).catch(() => null)
|
|
||||||
isFetching.value = false
|
state.value[name] = loadIcon(name)
|
||||||
}
|
.then((res) => { state.value[name] = res })
|
||||||
|
// We won't try to load this icon again if it fails
|
||||||
|
.catch(() => { state.value[name] = null })
|
||||||
|
|
||||||
|
// return an awaitable promise
|
||||||
|
return state.value[name]
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(() => {
|
||||||
|
watch(() => props.name, loadIconComponent, { immediate: true })
|
||||||
|
})
|
||||||
|
|
||||||
|
if (process.server) {
|
||||||
|
await loadIconComponent(props.name)
|
||||||
}
|
}
|
||||||
watch(() => props.name, loadIconComponent)
|
|
||||||
!component.value && (await loadIconComponent())
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
|
|||||||
Reference in New Issue
Block a user