mirror of
https://github.com/ArthurDanjou/ui.git
synced 2026-01-18 05:58:07 +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">
|
||||
import type { IconifyIcon } from '@iconify/vue'
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { Icon as Iconify } from '@iconify/vue/dist/offline'
|
||||
import { loadIcon } from '@iconify/vue'
|
||||
import { useNuxtApp, useState } from '#imports'
|
||||
import { useNuxtApp, useState, computed, watch, onMounted } from '#imports'
|
||||
|
||||
const props = defineProps({
|
||||
name: {
|
||||
@@ -20,19 +19,31 @@ const props = defineProps({
|
||||
})
|
||||
const nuxtApp = useNuxtApp()
|
||||
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 loadIconComponent = async () => {
|
||||
if (component.value) { return }
|
||||
if (!state.value?.[props.name]) {
|
||||
isFetching.value = true
|
||||
state.value[props.name] = await loadIcon(props.name).catch(() => null)
|
||||
isFetching.value = false
|
||||
}
|
||||
|
||||
const loadIconComponent = (name: string) => {
|
||||
state.value = state.value || {}
|
||||
if (nuxtApp.vueApp.component(props.name) || state.value[name] || state.value[name] === null) { return }
|
||||
|
||||
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 lang="ts">
|
||||
|
||||
Reference in New Issue
Block a user