☰
Vue笔记(十一)--插槽
2026/10/10 12:17:36 网站建设 项目流程

这一节了解一下Vue3中的插槽,它简单讲就是给子组件预留的“占位符”,允许父组件向子组件模板的指定位置注入自定义内容,实现组件结构与内容的解耦,总结如下:

API:

插槽:组件内预留的内容占位出口,让父组件可以向子组件内部传入自定义 HTML / 组件内容。

父:<template #插槽名>(v-slot:简写#) 子:<slot name="插槽名" :子数据="子数据"></slot>

栗子:

默认插槽

子组件 Card.vue <template> <div class="card"> <h3>通用卡片标题</h3> <slot> <p>卡片默认内容</p> </slot> </div> </template> <style scoped> .card { border:1px solid #ccc; padding:16px; width:300px; } </style>
父组件App.vue <script setup> import Card from './Card.vue' </script> <template> <!-- 父组件传入内容,填充到子组件默认slot位置 --> <Card> <p>我是父组件传入的卡片内容!</p> <button>按钮</button> </Card> <Card></Card> </template>

具名插槽

子组件Layout.vue <template> <div class="layout"> <header class="header"> <slot name="header"></slot> </header> <main class="main"> <slot></slot> </main> <footer class="footer"> <slot name="footer"></slot> </footer> </div> </template> <style scoped> .layout {width:400px;border:1px solid #eee;} .header{background:#f5f5f5;padding:8px;} .main{padding:12px;} .footer{background:#f5f5f5;padding:8px;text-align:center;} </style>
父组件App.vue <script setup> import Layout from './Layout.vue' </script> <template> <Layout> <template #header> <h4>页面头部</h4> </template> <p>主体区域内容</p> <template #footer> <span>©2026 版权信息</span> </template> </Layout> </template>

作用域插槽

子组件MyList.vue <template> <ul class="list"> <li v-for="item in list" :key="item.id"> <slot :row="item"> {{ item.name }} </slot> </li> </ul> </template> <script setup> const list = [ { id:1, name:'张三', age:20 }, { id:2, name:'李四', age:25 }, { id:3, name:'王五', age:30 } ] </script> <style scoped> .list {list-style:none;padding:0;} li {border-bottom:1px solid #eee;padding:8px;} </style>
父组件App.vue <script setup> import MyList from './MyList.vue' </script> <template> <h3>自定义列表渲染</h3> <MyList> <template #default="slotProps"> <div> <span>姓名:{{ slotProps.row.name }}</span> <span style="margin-left:20px">年龄:{{ slotProps.row.age }}</span> <button style="margin-left:10px">编辑</button> </div> </template> </MyList> </template>

注意:
1 编译作用域规则:插槽内容在父组件作用域中编译,只能访问父组件的数据,无法直接访问子组件的数据
2 具名插槽必须用<template> 包裹:v-slot/#只能写在<template>或组件标签上,不能直接写在普通元素上。

原理:
插槽本质不是“把 HTML片段传给子组件”,而是父组件提前生成渲染函数,把一段VNode节点函数传递给子组件;子组件在自身渲染阶段调用这个函数,生成VNode,最终挂载到slot出口位置。

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询