学习笔记:Vue——插槽
关于Vue插槽,只用过最简单的语法,现在完整地走一遍官方文档说明,并且探索更多用法。
01.如果组件中没有包含一个<slot>元素,则该组件起始标签和结束标签之间的任何内容都会被抛弃。
02.父级模板里的所有内容都是在父级作用域中编译的;子模板里的所有内容都是在子作用域中编译的。
03.后备(默认)内容
<button type="submit"> <slot>Submit</slot> </button>
04.具名插槽
<slot>元素有一个特殊的特性:name
<div class="container"> <header> <slot name="header"></slot> </header> <main> <slot></slot> </main> <footer> <slot name="footer"></slot> </footer> </div>
一个不带name的<slot>出口会带有隐含的名字"default"
05.作用域插槽
让插槽内容能够访问子组件中才有的数据是很有用的。
绑定在<slot>元素上的特性被称为插槽prop
<current-user> <template v-slot:default="slotProps"> {{ slotProps.user.firstName }} </template> </current-user>
独占默认插槽的缩写语法
<current-user v-slot="slotProps"> {{ slotProps.user.firstName }} </current-user>
只要出现多个插槽,请始终为所有的插槽使用完整的基于<template>的语法
<current-user> <template v-slot:default="slotProps"> {{ slotProps.user.firstName }} </template> <template v-slot:other="otherSlotProps"> ... </template> </current-user>
06.解构插槽Prop
<current-user v-slot="{ user }"> {{ user.firstName }} </current-user>
<current-user v-slot="{ user: person }"> {{ person.firstName }} </current-user>
<current-user v-slot="{ user = { firstName: 'Guest' } }"> {{ user.firstName }} </current-user>
07.动态插槽名
<base-layout> <template v-slot:[dynamicSlotName]> ... </template> </base-layout>
08.具名插槽的缩写#
<base-layout> <template #header> <h1>Here might be a page title</h1> </template> <p>A paragraph for the main content.</p> <p>And another one.</p> <template #footer> <p>Here's some contact info</p> </template> </base-layout>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理