插槽(Slots)(完整详细版)

一、匿名插槽

1.适用场景

子组件中只有一个位置允许父组件自定义内容

2.使用方法

第一步:在子组件中定义slot插槽

子组件 复制代码
<template>
  <div>
    <header>头部</header>
    <slot></slot>
    <footer>尾部</footer>
  </div>
</template>

第二步:在父组件中的子组件标签内直接填写需要插入的内容

父组件 复制代码
<template>
  <div>
    <TestComOne>
      <p>插入的新内容</p>
    </TestComOne>
  </div>
</template>

最终在子组件渲染出来的结果:

渲染 复制代码
<template>
  <div>
    <header>头部</header>
    <p>插入的新内容</p>
    <footer>尾部</footer>
  </div>
</template>

当父组件中没有提供插槽内容时,我们也可以给子组件的插槽中添加默认内容

添加默认内容 复制代码
<template>
  <div>
    <header>头部</header>
    <slot>默认内容</slot>
    <footer>尾部</footer>
  </div>
</template>

最终在子组件渲染出来的结果:

渲染 复制代码
<template>
  <div>
    <header>头部</header>
    默认内容
    <footer>尾部</footer>
  </div>
</template>

二、具名插槽

1.适用场景

子组件中有多个位置允许父组件自定义内容

2.使用方法

第一步:在子组件中定义多个slot插槽,并且为每个插槽添加一个特殊的attribute name

多个插槽 复制代码
<template>
  <div>
    <slot name="slotTop"></slot>
    <header>头部</header>
    <slot name="slotContent"></slot>
    <footer>尾部</footer>
    <slot name="slotBottom"></slot>
  </div>
</template>

第二步:在父组件中使用对应的插槽名

父组件中使用多个插槽 复制代码
<template>
  <div>
    <TestComOne>
      <template #slotTop>头部上面</template>
      <template #slotContent>中间</template>
      <template #slotBottom>尾部下面</template>
    </TestComOne>
  </div>
</template>

三、作用域插槽

1.为什么要使用作用域插槽

在某些场景下,我们想要插槽的内容使用到子组件域内的数据,这时候就需要用到插槽

2.使用方法

第一步:在子组件中,可以像组件传递props那样,向一个插槽slot传递attributes

子组件添加attributes 复制代码
<template>
  <div>
    <slot name="slotTop"></slot>
    <header>头部</header>
    <slot name="slotContent" height="180" :list="list"></slot>
    <footer>尾部</footer>
    <slot name="slotBottom"></slot>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
const list = ref({ name: "张三", old: 18 });
</script>

第二步:在父组件中使用解构赋值,拿到对应的值

父组件中使用 复制代码
<template>
  <div>
    <TestComOne>
      <template #slotContent="{ height, list }">
        <p>身高:{{ height }}</p>
        <p>姓名:{{ list.name }}</p>
        <p>年龄:{{ list.old }}</p>
      </template>
    </TestComOne>
  </div>
</template>

<script setup lang="ts">
import TestComOne from "./components/index.vue";
</script>
相关推荐
灵感__idea2 小时前
Hello 算法:贪心的世界
前端·javascript·算法
GreenTea3 小时前
一文搞懂Harness Engineering与Meta-Harness
前端·人工智能·后端
killerbasd4 小时前
牧苏苏传 我不装了 4/7
前端·javascript·vue.js
吴声子夜歌5 小时前
ES6——二进制数组详解
前端·ecmascript·es6
码事漫谈5 小时前
手把手带你部署本地模型,让你Token自由(小白专属)
前端·后端
ZC跨境爬虫5 小时前
【爬虫实战对比】Requests vs Scrapy 笔趣阁小说爬虫,从单线程到高效并发的全方位升级
前端·爬虫·scrapy·html
爱上好庆祝5 小时前
svg图片
前端·css·学习·html·css3
王夏奇6 小时前
python中的__all__ 具体用法
java·前端·python
大家的林语冰6 小时前
《前端周刊》尤大开源 Vite+ 全家桶,前端工业革命启动;尤大爆料 Void 云服务新产品,Vite 进军全栈开发;ECMA 源码映射规范......
前端·javascript·vue.js
jiayong237 小时前
第 8 课:开始引入组合式函数
前端·javascript·学习