When writing a component I often have the need to reuse small parts of logic.
As an example:
I get an integer from API and want to display a string instead.
I can do that with a small function in my code:
const mapIntegerToString = (i: number) => {
if (i === 0) return 'foo'
if (i === 1) return 'bar'
if (i === 2) return 'baz'
return 'unknown: ' + i
}
and use this function multiple times in the template
{{ mapIntegerToString(1) }}
Great
It keeps logic that is only relevant for this component within the component.
However, as soon as I don’t want to return a string, but something that requires a component, e.g. an icon, that does not work any more and I have to write a “sub component” in a separate file.
E.g.
<template>
<span>
<FooIcon v-if="i === 0" />
<BarIcon v-if="i === 1" />
<BazIcon v-if="i === 2" />
</span>
</template>
<script lang="ts" setup>
defineProps<{ i: number }>()
</script>
What I’d rather do is in my script part:
const mapIntegerToComponent = (i: number) => {
if (i === 0) return <FooIcon>
if (i === 1) return <BarIcon>
if (i === 2) return <BazIcon>
return <UnknownIcon>
}
and use that in my template as a component. Is that somehow possible?
I’ve looked into functional components and render functions, but as far as I understand it, this is only relevant if I don’t use a template in my component at all.