javascript - 将类添加到插槽范围
问题描述
我正在创建一个表格组件,并且我想让我的用户能够<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>
由于这个范围,有没有办法简单地将这个类添加到我的用户提供的所有内容中?
解决方案
您可以使用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 无效,因此您可以接受这种假设
推荐阅读
- powershell - Powershell:如何从 SearchResultEntry 对象的属性中获取 base64 值?
- css - 如何让 Vuetify v-flex 占据剩余的可用空间
- excel - 根据另一个值填充列
- common-table-expression - PonyORM:使用 WITH RECURSIVE CTE 子句而不编写原始 SQL(递归查询)
- java - 如何在 Spring Security 中的 SSO 登录后重定向我的上一页?
- jira - Maven 更改插件不适用于 Jira 云
- swift - RollingPitTabBar 背景问题 - Swift
- laravel - 如何使用 AWS CodePipeline 为 Laravel 应用程序正确创建 buildspec.yml 文件
- node.js - 了解 CosmosDB Gremlin API 中的“x-ms-request-charge”和“x-ms-total-request-charge”
- reactjs - 如何将父组件的react hook创建的引用传递给子组件?