组件插槽

@Slot

单插槽应用

[] 改进版权信息组件 copyright,增加一个 slot 接收使用者提供的 wxml,如使用图像组件
  1. 在组件中预留/创建插槽,调整结构如下
  2. <view class="copy">
        <slot></slot>
        <text>copyright 2023-2024</text>
    </view>
  3. 调整样式为弹性盒子垂直居中对齐;因为不确定使用者传递的是什么结构,所以不能指定插槽的样式
  4. .copy {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
    }
  5. 使用组件时,引入并使用组件,传递图像内容
  6. <view class="copy">
        <copy>
            <image class="img" src="../../utils/marker.png" mode="aspectFill" />
        </copy>
    </view>
  7. 使用者指定图像样式
  8. .img {
        width: 50px;
        height: 50px;
    }

多插槽应用

[] 改进版权信息组件copyright,再增加一个 slot 接收使用者的学号
  1. 在组件 js 选项中,启用多插槽 - 不是在 .json
  2. Component({
        properties: {},
        data: {},
        methods: {},
        options: {
            multipleSlots: true
        }
    })
  3. 在组件中预留/创建插槽,分配名字,调整结构如下
  4. <view class="copy">
        <slot name="img"></slot>
        <text>copyright 2023-2024</text>
        <slot name="sn"></slot>
    </view>
  5. 目标组件引入,使用 slot 指定插槽名称,并传递相应的内容
  6. <view class="copy">
        <copy>
            <image slot='img' class="img" src="../../utils/marker.png" mode="aspectFill" />
            <text slot='sn'>20221081</text>
        </copy>
    </view>
[] 商品组件 product