I have a component (IconInline.html
), within which I would like to import and render components dynamically based on a prop (IconID
) passed to it.
Currently I do it manually like this:
{{#if IconID === "A"}}
<A />
{{elseif IconID === "B"}}
<B />
{{elseif IconID === "C"}}
<C />
{{elseif IconID === "D"}}
<D />
{{/if}}
<script>
import A from "./icons/A.html";
import B from "./icons/B.html";
import C from "./icons/C.html";
import D from "./icons/D.html";
export default {
components: { A, B, C, D }
};
</script>
Is there a way to
There's no way to import all components in a given directory, but you can render components that match a specific prop using <svelte:component>
:
<svelte:component this={cmp} foo="bar" baz="bop">
<!-- contents go here -->
</svelte:component>
<script>
import A from "./icons/A.html";
import B from "./icons/B.html";
import C from "./icons/C.html";
import D from "./icons/D.html";
const components = { A, B, C, D };
export default {
computed: {
cmp: ({ IconID }) => components[IconID]
}
};
</script>
If IconID
was "A"
, that would be equivalent to
<A foo="bar" baz="bop">
<!-- contents go here -->
</A>
Docs here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With