在開發小程序的過程當中,常常會遇到一些很容易錯誤,而後容易忘記的一些知識點,所以,決定寫一篇文章來總結一下javascript
組件WXML中能夠用插槽來分發內容,例如:css
<view class='component'>
<slot></slot> //添加一個匿名插槽,用來承載其餘WXML結構
</view>
複製代碼
須要定義多個slot,須要在對應的組件js中聲明:前端
Component({
options:{
multipleSlots: true //當設置爲true,能夠支持在組件中設置多個slot
}
})
複製代碼
注:當在組件WXML中定義多個帶name屬性的slot,而沒有在對應組件js中配置multipleSlots: true,會致使頁面全部的插槽結構渲染失敗,例如:java
//子組件
<view class='component>
<view class='box1'>
<slot name='box1'></slot> //name屬性用來標識插槽
</view>
<view class='box2'>
<slot name='box'></slot>
</view>
</view>
//父組件(也叫引入組件的頁面)
<component>
<view slot='box1'></view> //slot的值對應子組件slot的name屬性值
<view slot='box2'></view> //當沒配置multipleSlots時,給兩處WXML都不會渲染到頁面中
</component>
複製代碼
另外當在組件的兩個位置,設置兩個匿名插槽時,會默認把內容渲染到最後一個slot中,例如:node
//子組件
<view class='component>
<view class='box1'>
<slot></slot> //添加一個匿名插槽
</view>
<view class='box2'>
<slot></slot> //添加一個匿名插槽
</view>
</view>
//父組件(也叫引入組件的頁面)
<component>
<view>這裏輸入內容...</view>
<view>這裏輸入內容...</view> //兩處內容都會插入子組件最後設置的slot位置處
</component>
複製代碼
組件對應的WXSS樣式,只對組件WXML中的節點生效,默認狀況下,組件WXML的樣式只受對應組件的WXSS影響(app.wxss 中的樣式、組件所在頁面的的樣式對自定義組件無效(除非更改組件樣式隔離選項或者標籤選擇器和其餘特殊選擇器))
注:當組件樣式和頁面樣式相互影響時,同等條件下,會適用組件中的樣式canvas
編寫樣式時,須要主要如下幾點:小程序
組件樣式styleIsolationapp
styleIsolation支持如下取值:xss
若是Component 構造器用於構造頁面 ,默認值爲 shared ,且還有如下幾個的樣式隔離選項可用:this
Component({
options:{
styleIsolation: 'isolated', //styleIsolation優先級高於addGlobalClass
addGlobalClass: true, //基礎庫版本 2.2.3 以上支持,等價於設置styleIsolation: apply-shared
}
})
複製代碼
固然在開發項目的過程當中,有一個例外,當組件中包含一個富文本的時候,例如:
//子組件
<view class="count_time">
<rich-text nodes="{{countHtml}}"></rich-text> </view>
//countHtml
<span class="shape">2</span><em class="st_txt">天</em>
<span class="shape">10</span><em class="st_txt">:</em>
<span class="shape">50</span><em class="st_txt">:</em>
<span class="shape">30</span>
//引用組件頁面
<count propA='...'></count>
複製代碼
想在引用組件的頁面複寫組件的樣式,經過設置styleIsolation: 'apply-shared',在頁面修改組件中富文本中class爲shape的樣式沒法生效,可是修改組件中不存在於富文本中內容能夠生效,經過設置styleIsolation: 'shared'可成功複寫組件中的樣式
最近在將以前作的一些小程序頁面的過程當中,遇到了一個很奇怪的問題,以下:
//一個彈框組件
<view class="pop_prop_box>
<view class="m_bot_box f_col">
<view class="service_titile" wx:if='{{viewTitle}}'>
<text class="txt">{{viewTitle}}</text>
</view>
<image class="icon-close" src='/static/newIcon/goods-close.png' bindtap="closePopup"></image> //絕對定位元素
</view>
</view>
//組件css
.pop_prop_box {
width: 100%;
height: 100%;
bottom: 0;
left: 0;
position: fixed;
z-index: 99;
}
.m_bot_box {
position: absolute;
z-index: 101; //z-index高於pop_prop_box
}
.icon-close {
position: absolute; //添加一個絕對定位的按鈕
top: 24rpx;
right: 24rpx;
z-index:100; //經過設置任意大於等於1的值觸發點擊事件
}
//組件js
Component({
methods: {
//關閉彈框
closePopup() {
this.setData({
showShare:false
})
}
}
})
複製代碼
定義一個遮罩層組件,在裏面添加一個絕對定位的按鈕,用於關閉彈框,點擊image沒法觸發點擊事件,把image用插槽的方式,定義在頁面中,則能夠觸發,最後經過在組件的class爲icon-close的元素的樣式上面添加一個z-index值(大於等於1)觸發了事件
這裏主要總結了幾種我在開發中遇到的一些問題和我容易忘記的一些知識點,比較簡單,可是俗話說,好記性不如爛筆頭,因此就但願作個記錄,也但願裏面一些我遇到的坑能夠幫助到其餘也遇到這些問題的人。這段時間也作了一些小程序前端生成圖片相關,過幾天會寫一個canvas生成圖片的一些知識點,以便於鞏固一下知識點