Create reusable VueJS Template to use as component named template slot

114 views Asked by At

I'm using PrimeFaces (PrimeVue) for my front end component UI.

For my main app layout I'm using several copies of the <Menubar> Component (docs link). This component has a template slot named #item which you can set to override how the items in the menu are rendered.

Since I have 3 or 4 different menus on the page and all have exact same #item slot template code, I would prefer to write the <template #item="{}"> code a single time, and then use it for the #item slot for each instance of <Menubar> on my page.

I tried following the instructions at https://vueuse.org/core/createReusableTemplate/ to create a template that I could use for this but something doesn't line up and the <Menubar> component acts as if I did not pass a <template #item> at all (as indicated by the fact it uses the built in display instead of the template provided).

I also tried making my own "component" that mimics the slot props and tried using that in place of the <template #item> tag and also as a child of it, and nothing I have tried seems to work.

It's not really the end of the world, but I am now just curious if this is something that is even possible and if so, I'm more curious as to how to accomplish it. Any time I can minimize duplicate code I will strive for it, no matter how big or small.

Here is an example of what I tried with createReusableTemplate:

<template>
    <div>
        <DefineTemplate name="#item" v-slot="{$slots, label, item, props, root, hasSubmenu}">
            <span v-if="condition">something</span>
            <span v-else="condition2">something else</span>
        </DefineTemplate>
        <Menubar :model="menuItems">
            <ReuseTemplate />
        </Menubar>
    </div>
</template>

I also tried specifying the main element like this:

<DefineTemplate #item="{ label, item, props, root, hasSubmenu }">

and just (without name="#item" or $slots):

<DefineTemplate v-slot="{ label, item, props, root, hasSubmenu }">

I also tried for the ReuseTemplate Element, things like:

<ReuseTemplate #item="{ label, item, props, root, hasSubmenu }" />

Obviously I'm not super clear on how the named slot props are set and corelate with these reusable template elements...

Is there a way to do what I am trying to do?

0

There are 0 answers