简体   繁体   English

将类别添加到广告位范围

[英]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. 我正在创建一个表组件,我想让我的用户能够添加自己的自定义<td>这要感谢一个插槽。 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) 问题是, veryImportantClass类对于我的组件是必需的,但我想避免要求用户在其创建的slot输入它(以降低复杂性)

Is there a way to simply add this class to all <td> given by my users thanks to this scope? 由于此作用域,有没有一种方法可以将此类简单地添加到我的用户给定的所有<td>

You could use the mounted() life-cycle hook to add the class using normal JavaScript functions. 您可以使用mounted()生命周期挂钩使用常规JavaScript函数添加类。 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. 如果广告位内容要更改,则可能需要对updated()做类似的事情。

Note: This does assume that the parent inserts <td> elements in the slot, which is not guaranteed. 注意:这确实假定父对象在插槽中插入<td>元素,但不能保证。 But since that would result in invalid HTML, you may be okay living with that assumption 但是由于那样会导致无效的HTML,因此您可以接受这种假设

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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