微信小程序slot不能在wx:for中使用的解决办法

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

https://developers.weixin.qq.com/s/ztPzoImW7E7P 

微信小程序使用`data-`属性可以在`wx:for`场景下传递事件参数。具体实现方法如下: 1. 在`wx:for`使用`template`标签定义模板。 2. 在模板定义使用`data-`属性传递需要传递的事件参数。 ```html <template name="list-item"> <view class="list-item" data-index="{{index}}" data-item="{{item}}" bindtap="onListItemTap"> <text>{{item}}</text> </view> </template> ``` 在上面的代码,我们在模板定义使用了`data-index`和`data-item`两个`data-`属性,分别传递了列表项的索引和值。 3. 在`wx:for`使用模板并传入数据。 ```html <view class="list"> <template wx:for="{{list}}" wx:for-item="item"> <template is="list-item" data="{{index: {{index}}, item: {{item}}}}"></template> </template> </view> ``` 在上面的代码,我们使用`wx:for`循环渲染`list`数组,然后在循环体使用`template`标签引入之前定义的模板,并通过`data`属性将需要传递的事件参数传入。 4. 在事件处理函数获取传递的参数。 ```javascript Page({ onListItemTap: function (event) { const index = event.currentTarget.dataset.index; const item = event.currentTarget.dataset.item; console.log(`点击了列表项${index},值为${item}`); }, }); ``` 在上面的代码,我们在事件处理函数通过`event.currentTarget.dataset`获取到传递的`data-`属性,然后获取到需要的参数值。 至此,在`wx:for`场景下使用`data-`属性传递事件参数的方法就介绍完了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值