uniapp slot的使用方法

在uniapp中如何使用slot?能否给个具体的使用示例?比如父组件如何向子组件传递内容,以及如何在子组件中接收和使用这些slot内容?另外,具名slot和默认slot在uniapp中的使用方式有什么区别?

2 回复

uniapp中slot是插槽,用于组件内容分发。
用法:

  1. 默认插槽:组件内写<slot></slot>,使用时传入内容。
  2. 具名插槽:组件内写<slot name="xxx"></slot>,使用时用<template v-slot:xxx>#xxx包裹内容。
  3. 作用域插槽:组件内通过<slot :data="data"></slot>传数据,使用时<template #default="props">接收。

在 UniApp 中,slot(插槽)是 Vue.js 框架提供的功能,用于实现组件的内容分发,允许父组件向子组件传递自定义内容。以下是基本使用方法:

1. 默认插槽

  • 子组件定义:使用 <slot> 标签占位。
    <template>
      <view>
        <slot></slot>
      </view>
    </template>
    
  • 父组件使用:在子组件标签内插入内容。
    <template>
      <child-component>
        <text>这是插入的内容</text>
      </child-component>
    </template>
    

2. 具名插槽

用于多个插槽的场景,通过 name 属性区分。

  • 子组件定义
    <template>
      <view>
        <slot name="header"></slot>
        <slot name="footer"></slot>
      </view>
    </template>
    
  • 父组件使用:用 v-slot# 指令指定插槽名。
    <template>
      <child-component>
        <template v-slot:header>
          <text>顶部内容</text>
        </template>
        <template #footer>
          <text>底部内容</text>
        </template>
      </child-component>
    </template>
    

3. 作用域插槽

允许子组件向父组件传递数据。

  • 子组件定义:通过 <slot> 的属性传递数据。
    <template>
      <view>
        <slot :data="itemData"></slot>
      </view>
    </template>
    <script>
    export default {
      data() {
        return {
          itemData: { message: "来自子组件的数据" }
        };
      }
    };
    </script>
    
  • 父组件使用:通过 v-slot 接收数据。
    <template>
      <child-component>
        <template v-slot="slotProps">
          <text>{{ slotProps.data.message }}</text>
        </template>
      </child-component>
    </template>
    

注意事项:

  • 在 UniApp 中,插槽用法与 Vue.js 一致,但需确保组件结构符合小程序规范(如避免嵌套过深)。
  • 默认插槽可简写为 #default

通过插槽,可以灵活定制组件内容,提升复用性。

回到顶部