Last active
August 24, 2024 19:34
-
-
Save james2doyle/ad966607aead9b9cfd1b15f599e3f039 to your computer and use it in GitHub Desktop.
Load an icon dynamically in Vue 3 using the import keyword and a ref
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- | |
Icon Component | |
Usage: | |
<icon icon="button"></icon> | |
--> | |
<template> | |
<transition name="fade" mode="out-in"> | |
<div v-if="!loadedIcon" class="w-4"> </div> | |
<component :is="loadedIcon" v-else v-once class="icon-wrapper" :name="icon" v-bind="$attrs" v-on="$listeners" /> | |
</transition> | |
</template> | |
<script lang="ts"> | |
import { defineComponent, ref } from '@vue/composition-api'; | |
interface Props { | |
icon: string | |
} | |
export default defineComponent<Props>({ | |
name: 'Icon', | |
props: { | |
icon: { | |
type: String as () => string, | |
required: true, | |
}, | |
}, | |
setup(props) { | |
const loadedIcon = ref(null); | |
// loads the icon dynamically | |
// assumes you have the ability to reference SVG as a component | |
import(`Assets/icons/${props.icon}.svg`) | |
.then((module) => { | |
loadedIcon.value = module.default; | |
}) | |
.catch(console.error.bind(console)); | |
return { props, loadedIcon }; | |
}, | |
}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment