作用:简单理解就是在子组件占个位置,等待父组件传入内容
1.基础内容插槽
首先我们需要在子组件中写入
//父组件
<test>
Hello Word
</test>
//子组件
<a href="#">
<slot></slot>
</a>
当组件渲染的时候,
插槽内也可以包含任何模板代码,包括HTML:
//父组件
<test>
<span class="fa fa-user"></span>
Hello Word
</test>
2.后备内容(默认内容)插槽
有时候我们需要给插槽设置一个具体的默认内容,当别的组件没有给你内容的时候,那么默认的内容就会被渲染
//子组件
//在slot插槽里设置默认内容 Submit
<button>
<slot>Submit</slot>
</button>
在父组件里直接使用test.vue如下,:那么最后设置的默认内容 Submit 将会被渲染:
//父组件
<test></test>
3.具名插槽
有时候我们一个组件里需要多个插槽,对于这样的情况,
//定义插槽的子组件
<div>
<header>
<!-- 我们希望把页头放这里 -->
</header>
<main>
<!-- 我们希望把主要内容放这里 -->
</main>
<footer>
<!-- 我们希望把页脚放这里 -->
</footer>
</div>
<div>
<header>
<slot name="header"></slot>
</header>
<main>
<slot></slot>
</main>
<footer>
<slot name="footer"></slot>
</footer>
</div>
//也可以使用v-slot指令
<div>
<template v-slot:header>
<h1>header</h1>
</template>
<p>content</p>
<template v-slot:footer>
<p>footer</p>
</template>
</div>
4.作用域插槽
父组件想访问插槽子组件的实例(作用域),可以使用作用域插槽
把需要传递的内容绑到
//带有插槽的子组件
<div>
<!-- 设置一个 usertext 然后把user绑到设置的 usertext 上 -->
<slot v-bind:usertext="user">{{user.lastName}}</slot>
</div>
...
//定义内容
data(){
return{
user:{
firstName:"Fan",
lastName:"Jun"
}
}
}
//父组件
//绑定在 <slot> 元素上的特性被称为插槽 prop。在父组件中,我们可以用 v-slot 设置一个值来定义我们提供的插槽 prop 的名字,然后直接使用就好了,:default可以去掉
//不能跟具名插槽同时使用,也就是在定义了default插槽的标签中不能v-slot:default="slotProps"的default不能写成其他名字
<div>
<!-- 可以把 :default 去掉,仅限于默认插槽 ,已经定义是default插槽-->
<test v-slot="slotProps">
{{slotProps.usertext.firstName}}
<!-- 无效,会警告 不能再拿其他插槽中的内容,需要另写标签-->
<template v-slot:other="otherSlotProps">
slotProps is NOT available here
</template>
</test>
</div>
//正确使用
<test>
<template v-slot:default="slotProps">
{{ slotProps.user.firstName }}
</template>
<template v-slot:other="otherSlotProps">
...
</template>
</test>
5.解构插槽Prop
在作用域插槽的基础上,把插槽传过来的值解构获取
<div>
<test v-slot={usertext}>
{{usertext.firstName}}
</test>
</div>
也可以重命名,usertext 重命名为 person:
<div>
<test v-slot={usertext:person}>
{{person.firstName}}
</test>
</div>
甚至定义默认值:
<div>
<test v-slot="{usertext={firstName:'Yang'}}">
{{usertext.firstName}}
</test>
</div>
6.具名插槽的缩写
跟 v-on 和 v-bind 一样,v-slot 也有缩写,即把参数之前的所有内容 (v-slot:) 替换为字符 #。例如 v-slot:header 可以被重写为 #header:
<div>
<template #header>
<h1>Here might be a page title</h1>
</template>
</div>
没有具体名字时不可缩写,必须要有明确插槽名
//错误写法
<test #="{ usertext }">
{{ usertext.firstName }}
</test>
//正确写法
<test #default="{ usertext }">
{{ usertext.firstName }}
</test>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异