需求:
在for循環(huán)的節(jié)點里像vue一樣使用slot并傳入?yún)?shù)。希望是如下的:
創(chuàng)建組件:list.wxml如下
<!-- list.wxml -->
<view wx:for="{{list}}" wx:key="index">
<slot item="{{item}}"></slot>
</view>
在頁面page.wxml使用組件,并給slot定義內(nèi)容如下
<!-- page.wxml -->
<list>
<block slot-scope="item">
<view>{{item}}</view>
</block>
</list>
然,微信小程序卻坑得你不省人事。
- 第一坑:不管你for多少個,它最終只渲染一個
- 第二坑:不支持傳參
于是,slot唯一的用處就是在指定的位置貼一塊固定代碼,是一個弱智的template引用,別無它用。
代替方案:抽象組件
將list.wxml組件改為:
<!-- list.wxml -->
<view wx:for="{{list}}" wx:key="index">
<item item="{{item}}"></item>
</view>
并在list.json中配置“componentGenerics"
{
"component": true,
"componentGenerics": {
"item": {
"default": "/components/default/default"
}
}
}
在page.wxml中使用:引入組件item,在list節(jié)點添加generic:item="item",第一個item表示抽象節(jié)點名稱,與list.wxml組件內(nèi)聲明的抽象節(jié)點名稱要一致;第二個“item”表示要插入的組件名,可以改為別的名稱,但要與usingComponents中配置的名稱一致。如下
<!-- page.wxml -->
<list generic:item="item"></list>
{
"usingComponents": {
"item": "../item/item"
}
}
創(chuàng)建item.wxml組件作為“插槽”內(nèi)容
<!-- item.wxml -->
<view>{{item}}</view>
Component({
properties: {
item: Object
}
})
解決!
這種功能本來就應(yīng)該給slot的解決的,小程序非得整個標(biāo)新立異。
那么問題來了,多層組件嵌套時,怎么搞?
對,就跟想象中的一樣,一層一層的配置componentGenerics和設(shè)置generic:xxx即可。