I'm new to Nuxt, I'm using Nuxt and Nuxt UI for my project. I'm trying to create helper methods to render the components with small differences. For example, in my Header.vue
<template>
<UBadge color="red" variant="subtle">Procedure Error</UBadge>
<UBadge color="yellow" variant="subtle">Temperature Warning</UBadge>
<UBadge color="yellow" variant="subtle">Density Warning</UBadge>
<UBadge color="green" variant="subtle">Init Success</UBadge>
...
</template>
I dont really want to define color and variant everytime I need to use it, the below is what I want
<template>
<ErrorBadge>Procedure Error</ErrorBadge>
<WarningBadge>Temperature Warning</WarningBadge>
<WarningBadge>Density Warning</WarningBadge>
<SuccessBadge>Init Success</SuccessBadge>
...
</template>
I've achieved this by creating a component for each type of the badge, but I think it is unnecessary to create a component for it, and there will be more different types of badge to be added. Is it possible to create functions to render the different badges? For example
const ErrorBadge = ...
const SuccessBadge = ...
const WarningBadge = ...
Thus there will be only 1 file for all of them.
Any help would be appreciated. Thanks!
Components can be defined dynamically, this requires to enable Vue build with runtime template compiler to use templates, render functions don't have such restriction. A project needs to be configured for JSX in order for it to be used in render function, but h()
works in any environment.
Functional components are suited for simple components with no state:
const ErrorBadge = (props, { slots }) => h(
UBadge,
{ color: "red", variant: "subtle", ...props },
slots.default?.()
);