Dynamically render a Vue component within another component
P粉764003519
P粉764003519 2023-08-30 20:51:07
0
2
540
<p>Using<strong>Vue 3.2.41</strong>-@heroicons/vue 2.0.14-inertiajs 1.0-vite 4.0.0</p> <p>I'm using this to call the Vue component: </p> <p><code><TimelineItem icon="CalendarDaysIcon" /></code></p> <p>The component looks like this: </p> <pre class="brush:php;toolbar:false;"><template> <component :is="icon" /> <!-- doesn't work --> <CalendarDaysIcon /> <!-- works --> </template> <script setup> import { CalendarDaysIcon, } from '@heroicons/vue/20/solid' const props = defineProps(['icon']) </script></pre> <p>The rendered HTML looks like this:</p> <pre class="brush:php;toolbar:false;"><calendardaysicon></calendardaysicon> <!-- not what I want --> <svg> ... </svg> <!-- correct but not dynamic --></pre> <p>In other words, when I want<code><component :is /></code> to render the component, it just renders some empty <code><calendardaysicon></code> ; mark. I can see that it has changed it to lowercase and I don't know how to force it back to PascalCase, I'm not even sure if that would help the situation. </p> <p>I've simplified the code a bit, but the full version will have a list of 10 different icons (all parts of the Heroicons package using PascalCase names) and I want to be able to call them easily from the main component.</p>
P粉764003519
P粉764003519

reply all(2)
P粉697408921

try:

P粉107772015

Use Use only strings containing CalendarDaysIcon

Instead, in the main component, pass the actual component reference like this:

<template>
  <TimelineItem :icon="CalendarDaysIcon" />
</template>

<script setup>
    import {
        CalendarDaysIcon,
    } from '@heroicons/vue/20/solid'

    const props = defineProps(['icon'])
</script>

Then, in the TimelineItem component, there is no need to reference any icon:

<template>
    <component :is="icon" /> <!-- now works -->
</template>

<script setup>
    const props = defineProps(['icon'])
</script>

Thanks to @Robert Boes on the Inertia Discord server for the guidance.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template