Vue组件间通信--插槽/slot(父传子)/3
作用:让父组件可以向子组件指定位置插入html结构,也是一种组件间通信的方式,适用于 父组件 ===> 子组件 。
父级模板里的所有内容都是在父级作用域中编译的;子模板里的所有内容都是在子作用域中编译的。
分类:默认插槽、具名插槽、作用域插槽
使用方式:
默认插槽:
父组件中:
<Category>
<div>html结构1</div>
</Category>
子组件中:
<template>
<div>
<!-- 定义插槽 -->
<slot>插槽默认内容...</slot>
</div>
</template>
具名插槽:
父组件
<base-layout>
<template v-slot:header>
<h1>这是一个标题</h1>
</template>
<p>主要内容的段落</p>
<p>再来一个</p>
<template v-slot:footer>
<p>这是一些联系方式</p>
</template>
</base-layout>
现在 <template>
元素中的所有内容都将会被传入相应的插槽。任何没有被包裹在带有 v-slot
的 <template>
中的内容都会被视为默认插槽的内容。
子组件
<div class="container">
<header>
<slot name="header"></slot>
</header>
<main>
<slot></slot>
</main>
<footer>
<slot name="footer"></slot>
</footer>
</div>
跟 v-on
和 v-bind
一样,v-slot
也有缩写,即把参数之前的所有内容 (v-slot:
) 替换为字符 #
。例如 v-slot:header
可以被重写为 #header
:
父组件
<base-layout>
<template #header>
<h1>这是一个标题</h1>
</template>
<p>主要内容的段落</p>
<p>再来一个</p>
<template #footer>
<p>这是一些联系方式</p>
</template>
</base-layout>
作用域插槽:
作用域插槽其实就是带数据的插槽,即带参数的插槽,简单的来说就是子组件提供给父组件的参数,该参数仅限于插槽中使用,父组件可根据子组件传过来的插槽数据来进行不同的方式展现和填充插槽内容。
子组件
为了让 games 在父级的插槽内容中可用,我们可以将 games 作为 <slot> 元素的一个 attribute 绑定上去:
<slot :games="games"></slot>
父组件
绑定在 <slot> 元素上的 attribute 被称为插槽 prop。
现在在父级作用域中,我们可以使用带值的 v-slot 来定义我们提供的插槽 prop 的名字:
<template v-slot='slotName'>
<div v-for="(item,index) in slotName.games" :key="index">{{item}}</div>
</template>
在这个例子中,我们选择将包含所有插槽 prop 的对象命名为 slotName,但你也可以使用任意你喜欢的名字。
效果:

独占默认插槽的缩写语法
当被提供的内容只有默认插槽时,组件的标签才可以被当作插槽的模板来使用
就是可以省略
template
<Hear v-slot:default="slotName">
<div v-for="(item,index) in slotName.games" :key="index">{{item}}</div>
</Hear>
解构插槽prop
可以使用 ES2015 解构来传入具体的插槽 prop,如下:
<Hear v-slot:default="{games}">
<div v-for="(item,index) in games" :key="index">{{item}}</div>
</Hear>
如果该插槽提供了多个 prop 的时候。它同样开启了 prop 重命名等其它可能,例如将 games 重命名为 game:
<Hear v-slot:default="{games:game}">
<div v-for="(item,index) in game" :key="index">{{item}}</div>
</Hear>
可以定义后备内容,用于插槽 prop 是 undefined 的情形:
<template v-slot:default="{games={games: '鸡架' }}">
<div v-for="(item,index) in games" :key="index">{{item}}</div>
</template>

动态插槽名
<template v-slot:[dynamicSlotName]>
...
</template>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了