Vue中的插槽

默认插槽(Default Slot):

  1. 单个默认插槽

    在子组件中使用 <slot></slot> 来定义一个默认插槽,父组件可在此处传递内容。

    1
    2
    3
    4
    5
    6
    <!-- ChildComponent.vue -->
    <template>
    <div>
    <slot></slot>
    </div>
    </template>
    1
    2
    3
    4
    5
    6
    <!-- ParentComponent.vue -->
    <template>
    <child-component>
    This content will be passed to the default slot.
    </child-component>
    </template>

具名插槽(Named Slot):

  1. 具名插槽

    可以使用 v-slot 指令和名称来定义具名插槽,使得父组件在填充内容时可以选择插入到指定位置。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    <!-- ChildComponent.vue -->
    <template>
    <div>
    <slot name="header"></slot>
    <div>
    <slot name="content"></slot>
    </div>
    </div>
    </template>
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    <!-- ParentComponent.vue -->
    <template>
    <child-component>
    <template v-slot:header>
    This is the header slot content.
    </template>
    <template v-slot:content>
    This is the content slot content.
    </template>
    </child-component>
    </template>
  2. 作用域插槽(Scoped Slot)

    使用带有参数的插槽可以向子组件传递数据,使父组件能够在插槽中访问子组件的数据。

    1
    2
    3
    4
    5
    6
    7
    8
    <!-- ChildComponent.vue -->
    <template>
    <ul>
    <li v-for="item in items" :key="item.id">
    <slot :item="item"></slot>
    </li>
    </ul>
    </template>
    1
    2
    3
    4
    5
    6
    7
    8
    <!-- ParentComponent.vue -->
    <template>
    <child-component :items="items">
    <template v-slot="{ item }">
    {{ item.name }}
    </template>
    </child-component>
    </template>

通过使用插槽,Vue.js 提供了一种强大的机制,允许开发者在父子组件之间传递内容并实现更灵活的组件化开发。开发者可以根据需要选择不同类型的插槽来满足项目中的需求。