[英]Add class to slot scope
我正在創建一個表組件,我想讓我的用戶能夠添加自己的自定義<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,因此您可以接受這種假設
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.