插槽(Slot)的使用方法

插槽是Vue.js中一个强大的功能,允许你在组件中预留位置,让父组件可以插入自定义内容。以下是插槽的主要使用方法:

基本插槽

<!-- 子组件 ChildComponent.vue -->
<template>
  <div>
    <h2>子组件标题</h2>
    <slot></slot>  <!-- 这里是插槽位置 -->
  </div>
</template>

<!-- 父组件使用 -->
<child-component>
  <p>这是插入到插槽中的内容</p>
</child-component>

具名插槽

<!-- 子组件 Layout.vue -->
<template>
  <div>
    <header>
      <slot name="header"></slot>
    </header>
    <main>
      <slot></slot>  <!-- 默认插槽 -->
    </main>
    <footer>
      <slot name="footer"></slot>
    </footer>
  </div>
</template>

<!-- 父组件使用 -->
<layout>
  <template v-slot:header>
    <h1>这是页眉</h1>
  </template>
  
  <p>这是主内容</p>
  
  <template v-slot:footer>
    <p>这是页脚</p>
  </template>
</layout>

作用域插槽

允许子组件向插槽传递数据:

<!-- 子组件 TodoList.vue -->
<template>
  <ul>
    <li v-for="(item, index) in items" :key="index">
      <slot :item="item" :index="index"></slot>
    </li>
  </ul>
</template>

<!-- 父组件使用 -->
<todo-list :items="todos">
  <template v-slot:default="slotProps">
    <span>{{ slotProps.index + 1 }}. {{ slotProps.item.text }}</span>
  </template>
</todo-list>

缩写语法

  • v-slot:header 可以缩写为 #header
  • 默认插槽可以缩写为 #default
<layout>
  <template #header>
    <h1>缩写语法</h1>
  </template>
  
  <p>默认内容</p>
  
  <template #footer>
    <p>页脚内容</p>
  </template>
</layout>

动态插槽名

<base-layout>
  <template v-slot:[dynamicSlotName]>
    ...
  </template>
</base-layout>

插槽提供了灵活的组件内容分发机制,是构建可复用组件的重要工具。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值