Dynamically render a Vue component within another component
P粉764003519
2023-08-30 20:51:07
<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>
try:
Use
Use only strings containingCalendarDaysIcon
Instead, in the main component, pass the actual component reference like this:
Then, in the
TimelineItem
component, there is no need to reference any icon:Thanks to
@Robert Boes
on the Inertia Discord server for the guidance.