一、元件模闆
元件模闆的寫法與頁面模闆相同。元件模闆與元件資料結合後生成的節點樹,将被插入到元件的引用位置上。
在元件模闆中可以提供一個 <slot> 節點,用于承載元件引用時提供的子節點。
1.無命名插槽
<!-- 元件模闆 -->
<view class="wrapper">
<view>這裡是元件的内部節點</view>
<slot></slot>
</view>
<!-- 引用元件的頁面模闆 -->
<view>
<component-tag-name>
<!-- 這部分内容将被放置在元件 <slot> 的位置上 -->
<view>這裡是插入到元件slot中的内容</view>
</component-tag-name>
</view>
2.命名插槽
預設情況下,一個元件的 wxml 中隻能有一個 slot 。需要使用多 slot 時,可以在元件 js 中聲明啟用。
Component({
options: {
multipleSlots: true // 在元件定義時的選項中啟用多slot支援
},
properties: { /* ... */ },
methods: { /* ... */ }
})
<!-- 元件模闆 -->
<view class="wrapper">
<slot name="before"></slot>
<view>這裡是元件的内部細節</view>
<slot name="after"></slot>
</view>
<!-- 引用元件的頁面模闆 -->
<view>
<component-tag-name>
<!-- 這部分内容将被放置在元件 <slot name="before"> 的位置上 -->
<view slot="before">這裡是插入到元件slot name="before"中的内容</view>
<!-- 這部分内容将被放置在元件 <slot name="after"> 的位置上 -->
<view slot="after">這裡是插入到元件slot name="after"中的内容</view>
</component-tag-name>
</view>
二、元件樣式
1.禁用寫法
元件對應 wxss 檔案的樣式,隻對元件wxml内的節點生效。以下寫法是不生效的
#a { } /* 在元件中不能使用 */
[a] { } /* 在元件中不能使用 */
button { } /* 在元件中不能使用 */
.a > .b { } /* 除非 .a 是 view 元件節點,否則不一定會生效 */
2.元件樣式隔離
預設情況下,自定義元件的樣式隻受到自定義元件 wxss 的影響。但也有些特殊寫法會影響到元件樣式就必須隔離
Component({
options: {
addGlobalClass: true,
styleIsolation: 'isolated'
}
})
3.外部樣式
有時,元件希望接受外部傳入的樣式類。此時可以在 Component 中用 externalClasses 定義段定義若幹個外部樣式類。
/* 元件 custom-component.js */
Component({
externalClasses: ['my-class']
})
<!-- 元件 custom-component.wxml -->
<custom-component class="my-class">這段文本的顔色由元件外的 class 決定</custom-component>
4.頁面樣式引用
.blue-text {
color: blue;
}
<view class="~blue-text"> 這段文本是藍色的 </view>
5.父元件樣式引用
.red-text {
color: red;
}
<view class="^red-text"> 這段文本是紅色的 </view>
6.虛拟化元件節點
Component({
options: {
virtualHost: true
},
properties: {
style: { // 定義 style 屬性可以拿到 style 屬性上設定的值
type: String,
}
},
externalClasses: ['class'], // 可以将 class 設為 externalClasses
})
<!-- 頁面的 WXML -->
<view style="display: flex">
<!-- 如果設定了 virtualHost ,節點上的樣式将失效 -->
<custom-component style="color: blue">不是藍色的</custom-component>
</view>