简体   繁体   中英

Add class to slot scope

I'm creating a table component, and I want to give the ability to my users to add their custom <td> thanks to a slot. So I have:

<tbody>
  <tr v-for="(item, key) in items">
    <slot :item=item">
      <td v-for="(header, headerKey) in variableHeaders"
        :class="{
            veryImportantClass: condition > 5,
        }">
        {{item.text}}
      </td>
    </slot>
  </tr>
</tbody>

And I use this slot thanks to this code:

<my-component
  :headers="headers"
  :items="items">
  <template slot-scope="prop">
    <td :class="{ aClassAddedByAUser: true }" v-for="(header, headerKey) in headers" ...>
      {{ prop.item.text }} with some text
    </td>
  </template>
</my-component>

The issue is, the veryImportantClass class is mandatory for my component, but I would like to avoid to ask my users to input it in their created slot (to decrease complexity)

Is there a way to simply add this class to all <td> given by my users thanks to this scope?

You could use the mounted() life-cycle hook to add the class using normal JavaScript functions. Here's how you could unconditionally add it to all cells. If you only need to add it to some cells, adjust accordingly.

mounted() {
    // wait a tick to ensure all child components have rendered
    this.$nextTick(() => {
        this.$el.querySelectorAll("td")
            .forEach(td => {
                td.classList.add("veryImportantClass");
            }
        }
    }
}

You might need to do something similar on updated() if the slot content is going to change.

Note: This does assume that the parent inserts <td> elements in the slot, which is not guaranteed. But since that would result in invalid HTML, you may be okay living with that assumption

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM