第9篇:插槽(Slots)的使用

目标:掌握组件内容分发的灵活方式


1. 默认插槽(匿名插槽)
html 复制代码
<!-- 子组件 Layout.vue -->  
<template>  
  <div class="container">  
    <header>  
      <slot></slot>  <!-- 内容插入点 -->  
    </header>  
  </div>  
</template>  

<!-- 父组件使用 -->  
<Layout>  
  <h1>这是插入的标题内容</h1>  
</Layout>  
复制代码

关键点

  • <slot> 标签定义内容占位符

  • 父组件传入的内容会替换子组件的 <slot>


2. 具名插槽
html 复制代码
<!-- 子组件 Card.vue -->  
<template>  
  <div class="card">  
    <slot name="header"></slot>  
    <slot name="content"></slot>  
    <slot name="footer"></slot>  
  </div>  
</template>  

<!-- 父组件使用 -->  
<Card>  
  <template v-slot:header>  
    <h2>卡片标题</h2>  
  </template>  

  <template #content>  <!-- 简写语法 -->  
    <p>卡片正文内容...</p>  
  </template>  

  <template #footer>  
    <button>确认</button>  
  </template>  
</Card>  
复制代码

语法说明

  • v-slot:name 或简写 #name 指定插槽名称

  • 未命名的 <template> 内容会填充到默认插槽


3. 作用域插槽(向父组件传递数据)
html 复制代码
<!-- 子组件 TodoList.vue -->  
<template>  
  <ul>  
    <li v-for="todo in todos" :key="todo.id">  
      <slot :todo="todo"></slot>  
    </li>  
  </ul>  
</template>  

<!-- 父组件使用 -->  
<TodoList :todos="todoList">  
  <template #default="slotProps">  
    <span :class="{ done: slotProps.todo.isDone }">  
      {{ slotProps.todo.text }}  
    </span>  
  </template>  
</TodoList>  
复制代码

关键点

  • 子组件通过 <slot :data="value"> 传递数据

  • 父组件通过 #slotName="props" 接收数据


4. 插槽默认内容
html 复制代码
<!-- 子组件 Button.vue -->  
<template>  
  <button class="btn">  
    <slot>提交</slot>  <!-- 父组件不传内容时显示"提交" -->  
  </button>  
</template>  
复制代码

5. 动态插槽名(Vue3新特性)
html 复制代码
<template>  
  <Component>  
    <template #[dynamicSlotName]>  
      动态插槽内容  
    </template>  
  </Component>  
</template>  

<script setup>  
const dynamicSlotName = ref('header')  
</script>  

6. 插槽实战场景
  1. 布局组件:定义页面的通用结构(Header/Content/Footer)

  2. UI组件库:Table组件的自定义单元格渲染

  3. 高阶组件:通过作用域插槽传递业务数据


最佳实践

  • 复杂组件优先使用具名插槽

  • 避免在插槽内容中直接修改子组件状态

  • 作用域插槽适合需要定制渲染逻辑的场景

相关推荐
IT_陈寒2 小时前
JavaScript项目实战经验分享
前端·人工智能·后端
用户47949283569153 小时前
6w star,GitHub 趋势第一的 Ponytail,这个agent插件到底在火什么
前端·后端
薛定喵的谔4 小时前
我开源了一个精致的 Next.js 博客模板:Skyplume
前端·前端框架·next.js
张龙6875 小时前
构建生产级 AI Agent:工具调用与记忆架构实战指南
前端
kyriewen6 小时前
2026 年了,还在用 Node.js?Bun 迁移实战:20 分钟搞定,附踩坑记录
前端·javascript·node.js
青山Coding7 小时前
Cesium应用(八):物体运动的实现思路
前端·cesium
用户41659673693557 小时前
Android WebView 加载 file:// 离线页面调试教程
android·前端
Asmewill7 小时前
curl命令学习笔记一
前端
我是一只快乐的小螃蟹7 小时前
1.2 ArrayList 源码解析
前端
星栈7 小时前
我用 Rust + Dioxus 做了个全栈跨平台笔记应用:再把新建、编辑和交付补上
前端·rust·前端框架