Search code examples
vue.jsvue-component

How can I inject template into a slot


In vue 2.7 I have a table component

<template>
    <table>
        <tbody>
            <slot name="tbody"></slot>
        </tbody>
    </table>
</template>

Using this component like so:

<my-table>
    <template #tbody>
         <tr v-for="employee in employees" :key="employee.id">
              <td>{{ employee.name }}</td>
              <td>{{ employee.occupation }}</td>
         </tr>
     </template>
</my-table>

Now in the component I want to add a checkbox for every row in the template supplied from outside the component. Is it possible? How?


Solution

  • Yes, it's possible, but complicated. You will need to manually process your slots and render them again using Vue Render Functions.

    Check for example this How to clear "Slot 'default' invoked outside of the render function" warning? Vue3, Composition API on how to process passed slots in a component.

    It's a lot of work. I would suggest you rethink your design.

    Check how popular Vue Libraries, like Quasar, Vuetify, PrimeVue, Element+ design the Tables.

    They mostly pass data to a table component and provide slots for cells.