Use of WeChat Mini Program Slots

Foreword : I heard someone tell me that the WeChat applet has no component slot function. Haha, let’s see what it is!
Here I sort out how to use slots of WeChat applet components:

1. Single slot (basic use)

Component templates are written in the same way as page templates. The node tree generated by the combination of component template and component data will be inserted into the reference position of the component.

A node can be provided in the component template to host the child nodes provided when the component is referenced.

Custom component template:

<!-- 组件模板 -->
<view class="mycomponent">
  <view>这里是组件的内部节点</view>
  <slot></slot>
</view>

The page template that references the component:

<!-- 引用组件的页面模板 -->
<view>
  <mycomponent>
    <!-- 这部分内容将被放置在组件 <slot> 的位置上 -->
    <view>这里是插入到组件 slot 中的内容</view>
  </mycomponent>
</view>

The content in the custom component tag will be placed at the position <slot>of

A component template is equivalent to:

<!-- 引用组件的页面模板 -->
<view class="mycomponent">
  <view>这里是组件的内部节点</view>
  <view>这里是插入到组件 slot 中的内容</view>
</view>

2. Multiple slots (named slots)

By default, there can only be one slot in a component's wxml. When you need to use multiple slots, you can declare and enable them in the component js.

Custom component js:

Component({
    
    
  options: {
    
    
    multipleSlots: true // 在组件定义时的选项中启用多 slot 支持
  },
})

At this point, multiple slots can be used in the wxml of this component, distinguished by different names.

Custom component template:

<!-- 组件模板 -->
<view class="mycomponent">
  <slot name="before"></slot>
  <view>这里是组件的内部节点</view>
  <slot name="after"></slot>
</view>

When used, use the slot attribute to insert nodes into different slots.

The page template that references the component:

<!-- 引用组件的页面模板 -->
<view>
  <mycomponent>
    <!-- 这部分内容将被放置在组件 <slot name="before"> 的位置上 -->
    <view slot="before">这里是插入到组件slot name="before"中的内容</view>
    <!-- 这部分内容将被放置在组件 <slot name="after"> 的位置上 -->
    <view slot="after">这里是插入到组件slot name="after"中的内容</view>
  </mycomponent>
</view>

The effect is equivalent to:

<view class="mycomponent">
  <view slot="before">这里是插入到组件slot name="before"中的内容</view>
  <view>这里是组件的内部节点</view>
  <view slot="after">这里是插入到组件slot name="after"中的内容</view>
</view>

Guess you like

Origin blog.csdn.net/weixin_44646763/article/details/127746707