vue3 学习笔记12 -- 插槽的使用

vue3 学习笔记12 – 插槽的使用

插槽(Slots)是一种让父组件能够向子组件传递标记的方法。通过定义插槽,子组件可以预留出可由父组件控制的区域,这样父组件就可以向这些区域填充自己的内容。

假设我们有一个父组件 ParentComponent 和一个子组件 ChildComponent

默认插槽(Default Slot)

默认插槽是最基本的插槽形式,允许父组件在子组件中插入任意内容,而子组件则可以通过 来渲染这些内容。

  • ParentComponent.vue
<template>
  <div>
    <h2>Parent Component</h2>
    <ChildComponent>
      <!-- 这里是默认插槽 -->
      <p>Content inside parent component</p>
    </ChildComponent>
  </div>
</template>

<script setup lang="ts">
import ChildComponent from './ChildComponent.vue';
</script>

  • ChildComponent.vue
<template>
  <div>
    <h3>Child Component</h3>
    <slot></slot>
  </div>
</template>

<script setup lang="ts">
// TypeScript setup syntax
</script>


  • 上述例子
    • ParentComponent 包含了 ChildComponent,并传递了一些内容作为默认插槽。
    • ChildComponent 中使用了 来显示来自父组件的内容。

具名插槽(Named Slots)

具名插槽允许父组件在子组件中定义多个插槽位置,使得父组件可以将不同的内容分发到不同的插槽中。这种方式特别适合需要布局或者结构化控制的场景。

  • ParentComponent.vue
<template>
  <div>
    <h2>Parent Component</h2>
    <ChildComponent>
      <!-- 具名插槽 -->
      <template #header>
        <h3>Header in Parent</h3>
      </template>
      <template #footer>
        <p>Footer in Parent</p>
      </template>
    </ChildComponent>
  </div>
</template>

<script setup lang="ts">
import ChildComponent from './ChildComponent.vue';
</script>


  • ChildComponent.vue
<template>
  <div>
    <h3>Child Component</h3>
    <slot name="header"></slot>
    <slot name="footer"></slot>
  </div>
</template>

<script setup lang="ts">
// TypeScript setup syntax
</script>


  • 上述例子
    • ParentComponent 通过使用 <template #header> 和 <template #footer> 来定义具名插槽的内容
    • ChildComponent 中使用了 和 来渲染具名插槽的内容。

作用域插槽

子组件向父组件传递数据的一种形式,子组件在具名标签或者匿名标签上绑定数据,父组件在标签上获取数据

  • ParentComponent.vue
<template>
  <div>
    <ChildComponent v-slot="{ text,count }">
     <div>{{ text }}---{{ count }}</div>
    </ChildComponent>
  </div>
</template>

<script setup lang="ts">
import ChildComponent from './ChildComponent.vue';

const message = 'Hello from Parent';
</script>


  • ChildComponent.vue
<template>
  <div>
    <p>我是子组件</p>
    <slot text="我是子组件" :count="1"></slot>
  </div>
</template>


  • 8
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值