首页 > 解决方案 > 将类添加到插槽范围

问题描述

我正在创建一个表格组件,并且我想让我的用户能够<td>通过插槽添加他们的自定义。所以我有:

<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>

由于这段代码,我使用了这个插槽:

<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>

问题是,veryImportantClass该类对于我的组件是强制性的,但我想避免要求我的用户在他们创建的中输入它slot(以降低复杂性)

<td>由于这个范围,有没有办法简单地将这个类添加到我的用户提供的所有内容中?

标签: javascriptvue.jsvuejs2

解决方案


您可以使用mounted()生命周期钩子使用普通的 JavaScript 函数添加类。这是您可以无条件地将其添加到所有单元格的方法。如果您只需要将其添加到某些单元格中,请进行相应调整。

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

updated()如果插槽内容要更改,您可能需要执行类似的操作。

注意:这确实假设父级<td>在插槽中插入元素,这是不保证的。但是由于这会导致 HTML 无效,因此您可以接受这种假设


推荐阅读