v-slot指令用于定义插槽内容,尤其在使用具名插槽时非常关键。具名插槽允许组件内部预留多个插槽位置,如卡片组件的标题、内容和底部操作区域。1. 在子组件中通过

在 Vue 中,
v-slot
指令用于定义插槽内容,特别是在使用具名插槽(named slots)时非常关键。简单来说,
v-slot
帮我们指定某一块 HTML 内容应该插入到组件的哪个插槽位置。
什么是具名插槽?
在组件开发中,有时候我们需要在组件内部预留多个插槽位置。比如一个卡片组件,可能希望分别允许父组件传入标题、内容和底部操作区域的内容。这时就需要用到具名插槽。
<!-- MyCard.vue -->
<template><div class="card">
<div class="card-header">
<slot name="header"></slot>
</div>
<div class="card-body">
<slot></slot><!-- 默认插槽 -->
</div>
<div class="card-footer">
<slot name="footer"></slot>
</div>
</div>
</template>
这样,父组件就可以通过
v-slot
来分别填充不同位置的内容。
如何在父组件中使用 v-slot 指定具名插槽
在父组件中使用
<mycard></mycard>
组件时,可以通过
v-slot
指定要填充的插槽名称:
将静态 Vue 页面(index.vue)改造为动态页面(Custom.vue);稿源仅限 index.vue、其引用的 CSS 与资源路径,禁止参考仓库内其他文件。Invoke when user wants to transform a static Vue page into a dynamic data-driven page with Element UI components.
<template><mycard><template v-slot:header><h2>这里是标题</h2>
</template><p>这是默认插槽的内容</p>
<template v-slot:footer><button>提交</button>
</template></mycard></template>
-
v-slot:header
表示这个模板块会插入到子组件中名为header
的插槽。 - 如果不写
name
,就是插入默认插槽。 - 注意:每个
template
标签包裹的是对应插槽的内容。
简写语法:用 # 替代 v-slot:
Vue 提供了更简洁的写法:使用
#
替代
v-slot:
,这在实际开发中更常见:
<template><mycard><template><h2>标题部分</h2>
</template><p>默认插槽内容</p>
<template><span>底部信息</span>
</template></mycard></template>
这种写法看起来更清爽,也更容易阅读。
使用场景和注意事项
- 组件复用性强:当你封装一个通用组件(如表格、弹窗、导航栏等),需要支持灵活内容插入时,具名插槽非常有用。
-
避免插槽命名冲突:插槽名称建议使用语义明确的单词,如
header
、actions
、default
等,不要重复或过于随意。 -
可以传递数据给插槽(进阶):你还可以通过
slotProps
向插槽传递数据,实现更灵活的插槽内容控制。 - 注意作用域问题:插槽中的变量只在当前插槽内有效,不能跨插槽访问。
基本上就这些。掌握了
v-slot
和具名插槽的配合使用,就能更好地构建可定制化的组件结构了。
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!










