Search code examples
vuejs2custom-component

vuejs 2 component design


I created a vuejs table standalone component like:

<template>
    <header-with-many-specific-options/> *
    <generic-table/> *
</template>
<script>
    export default {
      data() {
        return {}
     }
  } 
etc.
</script>

* These aren't components but a representation of my messy template structure.

Now I want to turn my table into a reusable component and in order to do that I want to seperate the very specific header from the generic table, so I can swap in headers depending on what I need. The header could have a table search, pagination or buttons for example.

Example:

<table-component>
    <user-table-header> <- can swap out
</table-component>

So yeah, is there a way to achieve this?


Solution

  • Use slots. They're basically a placeholder for content within a component that can be specified within the tag for the component.

    In your table component definition, you'd specify where you want to put the header content like this:

    <template>
      <slot name="header"></slot>
      <generic-table></generic-table>
    </template>
    

    Then, wherever you use the component tag, add the slot attribute with the name "header" as the value to the element you want to go in the slot:

    <table-component>
      <user-table-header slot="header"></user-table-header>
    </table-component>