Jing
Jing

Reputation: 700

Slot Content Distribution of Table Component using Vuejs

I want to create a table component that distribute styling columns through colgroup and col tags and let who use the component can override how tbody content rendered. I use named slot in Vuejs but It dose not work (the colgroup and table body content slot seem not to replace with the user's content) here the code.

HTML

<body>

  <div id='app'>
    <simple-table>
      <colgroup slot='colstyle'>
        <col style='background-color: yellow;'>
      </colgroup>
      <h2 slot='above-table'>
    Above Table Content Modified
    </h2>
      <tbody slot='tbody-content'>
        <tr>
          <td>override 1</td>
          <td>override 2</td>
          <td>override 3</td>
          <tr>
      </tbody>
    </simple-table>
  </div>


  <script id='simple-table' type='x-template'>
    <slot name='above-table'>
      Default Above Table Content
    </slot>
    <table>
      <slot name='colstyle'>
        <colgroup>
          <col span='2' style='background-color: red;'>
        </colgroup>
      </slot>
      <thead>
        <tr>
          <th>First</th>
          <th>Second</th>
          <th>Third</th>
        </tr>
      </thead>
      <slot name='tbody-content'>
        <tbody>
          <tr>
            <td>xxx</td>
            <td>yyy</td>
            <td>zzz</td>
          </tr>
        </tbody>
      </slot>
    </table>
  </script>
</body>

Javascript

Vue.component('simple-table', {
  template: '#simple-table'
});

var app = new Vue({
  el: "body"
});

on jsfiddle

Is there any better solution for this. Thank in advanced.

Upvotes: 1

Views: 1816

Answers (1)

Yerko Palma
Yerko Palma

Reputation: 12329

I guess that the problem is how html works. In Vuejs guide, says that

Some HTML elements, for example <table>, has restrictions on what elements can appear inside it

That's why they created the special is attribute. But notice that in your case, you can't use

    <colgroup is='colstyle'>
      <col span='2' style='background-color: red;'>
    </colgroup>

Because colstyle is the name of a slot, not a custom component. So what I would do would be create small custom components for those slots, and add them through the is attribute

Upvotes: 1

Related Questions