slot,Vue中叫做插槽,是向组件中插入内容的容器。小程序是支持动态slot的。

下面使用动态插槽建立一个完整的tab切换组件。

建立组件

组件的路径为components/tabSwitcher/tab-switcher

启用多slot支持

在组件的.js文件中添加下面代码:

options:{
  multipleSlots: true
}

定义组件的properties

在组件的.js文件中添加下面的代码:

properties: {
  titleList: Array
}

组件WXML

<view class='tab-box'>
  <view class='tab active' wx:for='{{titleList}}'>{{item.title}}</view>
</view>
<view class='tab-list-box'>
  <swiper class='tab-swiper'>
    <swiper-item class='tab-swiper-item'  wx:for='{{titleList.length}}'>
      <scroll-view class='tab-scroll-view' scroll-y>
        <!-- 这里就是重点,组件会生成多个slot,个数等于titleList的长度 -->
        <!-- 名称分别是slot0、slot1...slot[titleList.length - 1] -->
        <slot name='slot{{index}}'></slot>
      </scroll-view>
    </swiper-item>
  </swiper>
</view>

组件WXSS

.tab-box {
  position: fixed;
  left: 0;
  top: 0;
  right: 0;
  display: flex;
  justify-content: space-around;
  height: 90rpx;
  line-height: 90rpx;
  text-align: center;
}

.tab-box .tab {
  flex: auto;
  font-size: 26rpx;
  color: #191919;
}

.tab-box .tab.active {
  position: relative;
  font-size: 30rpx;
  font-weight: bold;
}

.tab-box .tab.active::after {
  content: '';
  position: absolute;
  left: 50%;
  bottom: 0;
  transform: translateX(-50%);
  height: 4rpx;
  width: 48rpx;
  background-color: #00bb2c;
}

.tab-list-box {
  height: 100%;
  box-sizing: border-box;
  padding-top: 90rpx;
}

.tab-list-box .tab-swiper, .tab-list-box .tab-swiper-item {
  height: 100%;
}

.tab-list-box .tab-scroll-view {
  height: 100%;
}

使用组件

在页面的.json文件中引用组件:

"usingComponents": {
  "TabSwitcher":"../components/tabSwitcher/tab-switcher"
}

定义组件需要的数据

在页面的.js文件中添加下面的代码:

data: {
    titleList: [{
      title: '未开始'
    },
    {
      title: '进行中'
    },
    {
      title: '已结束'
    }
  ]
}

在页面WXML中使用组件:

<TabSwitcher titleList='{{titleList}}'>
  <!-- 这里就是动态生成的slot内容,名称和组件的slot name一一对应 -->
  <view wx:for='{{titleList.length}}' slot='slot{{index}}'>
    <!-- 这里放自己需要的内容 -->
    {{item}}
  </view>
</TabSwitcher>

最后的效果是这样的:

record.gif

这里代码还未完善,tab都是active的样式

总结

微信小程序的文档中并没有写明slot支持动态生成。
实现类似的功能也有很多途径,不一定非要用动态slot

标签: 微信小程序自定义组件, 动态slot