微信小程序——插槽slot

插槽(slot)是一种用于在父组件中插入子组件内容的机制。通过使用插槽,我们可以实现组件的复用和灵活性。

在父组件中,我们可以将具体的内容放置在插槽中,并在子组件中使用插槽来展示这些内容。插槽允许父组件在渲染子组件时向其传递内容,使得子组件能够根据具体情况展示不同的内容。

一、匿名插槽

以components中创建的SlotAnony 和pages中的features为例

features.json

{
    "usingComponents": {
        "if-comp":"/components/IfComp/IfComp",
        "for-comp":"/components/ForComp/ForComp",
        "block-comp":"/components/BlockComp/BlockComp",
        "slot-anony":"/components/SlotAnony/SlotAnony"
    },
    "navigationBarTitleText": "语法特点",
    "navigationBarBackgroundColor": "#FFF",
    "navigationBarTextStyle": "black"
}

 features.wxml

<view>===========条件渲染=============</view>
<if-comp />
<view>===========循环遍历=============</view>
<for-comp />
<view>===========空标签=============</view>
<block-comp></block-comp>
<view>===========匿名插槽=============</view>
<slot-anony>
    <view>1111</view>
    <view>2222</view>
</slot-anony>

SlotAnony.wxml

<view class="layout">
    <view>top</view>
    <slot></slot>
    <view>footer</view>
</view>

SlotAnony.wxss

.layout{
    background: green;
    height: 100px;
    color: #fff;
}

运行效果

 二、具名插槽

注意,当一个组件中存在多个插槽时,需要在.js文件中将multipleSlots设为true

以components中创建的SlotName 和pages中的features为例

 SlotName.wxml   (view里面有三个slot)

<view class="layout">
    <view class="left">
        <slot name="left"></slot>
    </view>
    <view class="middle">
        <slot name="middle"></slot>
    </view>
    <view class="right">
        <slot name="right"></slot>
    </view>
</view>

 SlotName.wxss

.layout{
    background: cyan;
    height: 80px;
    display: flex;
    justify-content: space-between;
    color: #fff;
}

.right{
    background: grey;
}
.left{
    background: red;
}

SlotName.js

Component({
    options:{
        multipleSlots:true
    }
})

features.wxml

<view>===========条件渲染=============</view>
<if-comp />
<view>===========循环遍历=============</view>
<for-comp />
<view>===========空标签=============</view>
<block-comp></block-comp>
<view>===========匿名插槽=============</view>
<slot-anony>
    <view>1111</view>
    <view>2222</view>
</slot-anony>
<view>===========具名插槽=============</view>
<slot-name>
    <view slot="right">右侧</view>
    <view slot="left">左侧</view>
    <view slot="middle">中间</view>
</slot-name>

features.json

{
    "usingComponents": {
        "if-comp":"/components/IfComp/IfComp",
        "for-comp":"/components/ForComp/ForComp",
        "block-comp":"/components/BlockComp/BlockComp",
        "slot-anony":"/components/SlotAnony/SlotAnony",
        "slot-name":"/components/SlotName/SlotName"
    },
    "navigationBarTitleText": "语法特点",
    "navigationBarBackgroundColor": "#FFF",
    "navigationBarTextStyle": "black"
}

运行效果

猜你喜欢

转载自blog.csdn.net/weixin_58963766/article/details/131626214
今日推荐