slot不能在wx:for中使用, 他只渲染第一个
用虚拟节点可以比较好的解决此问题,只是多了一步,需要把插入的内容做成组件:
比如组件 selectable-group 中wx:for中有个slot
<view wx:for="{{labels}}" wx:key="*this">
<label bindtap="itemTap" data-index="{{index}}">
<slot name='xxx'></slot>
{{item}}
</label>
</view>
但如果直接这样,使用时发现只渲染第一个,
1、 所以改成虚拟节点形式, 如下:(其中 xnjd 是自定义的名称)
<view wx:for="{{labels}}" wx:key="*this">
<label bindtap="itemTap" data-index="{{index}}">
<xnjd disabled="{{false}}" selected="{{selected[index]}}"></xnjd>
{{item}}
</label>
</view>
但需要再 selectable-group.json中声明 xnjd
{
"component": true,
"usingComponents": {},
"componentGenerics": {
"xnjd": true
}
}
2、把本来需要在wx:for中的slot插入的内容,做成一个个组件,把本来用slot插入的做成组件, 如下图:
3、在页面中使用,比如在index中使用
首先需要在index.json中引用selectable-group组件、以及要插入的组件
{
"usingComponents": {
"selectable-group": "./selectable-group",
"custom-radio": "./custom-radio",
"custom-checkbox": "./custom-checkbox"
}
}
index.wxml中:
在组件中指定要插入的组件名称,格式为 generic:xnjd="子组件名称" 其中 xnjd 是你自己起的那个虚拟节点名字
<view> custom-radio</view>
<selectable-group generic:xnjd="custom-radio" />
<view> custom-checkbox</view>
<selectable-group generic:xnjd="custom-checkbox" />
效果:
注意事项
- 节点的 generic 引用
generic:xxx="yyy"
中,值yyy
只能是静态值,不能包含数据绑定。因而抽象节点特性并不适用于动态决定节点名的场景。
源码: https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/generics.html