我正在创建一个表组件,我想让我的用户能够添加自己的自定义<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>
中?
答案 0 :(得分:1)
您可以使用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,因此您可以接受这种假设