Skip to content

Instantly share code, notes, and snippets.

@james2doyle
Last active October 24, 2022 15:15
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save james2doyle/ad966607aead9b9cfd1b15f599e3f039 to your computer and use it in GitHub Desktop.
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
<!--
Icon Component
Usage:
<icon icon="button"></icon>
-->
<template>
<transition name="fade" mode="out-in">
<div v-if="!loadedIcon" class="w-4">&nbsp;</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