Vue 实现了一套内容分发的 API,这套 API 的设计灵感源自于 Web Components 规范草案,将
元素作为承载分发内容的出口。
简而言之,slot 就是用来为子组件分发渲染内容的,具有作用域的 component,又名插槽。
注释:在 2.6.0 中,我们为具名插槽和作用域插槽引入了一个新的统一的语法 (即 v-slot 指令)。它取代了 slot 和 slot-scope 这两个目前已被废弃但未被移除且仍在文档中的特性。新语法的由来可查阅这份 RFC。
使用方法
官方文档例子
<div class="container"><header><!-- 我们希望把页头放这里 --></header><main><!-- 我们希望把主要内容放这里 --></main><footer><!-- 我们希望把页脚放这里 --></footer></div
我们可以通过
<div class="container"><header><slot name="header"></slot></header><main><slot></slot></main><footer><slot name="footer"></slot></footer></div
注意⚠️:如果 slot 不带 name,则默认为 default 值。
向具名插槽分发内容时,我们可以在一个
<base-layout><template v-slot:header><h1>Here might be a page title</h1></template><p>A paragraph for the main content.</p><p>And another one.</p><template v-slot:footer><p>Here's some contact info</p></template></base-layout>
渲染结果:
<div class="container"><header><h1>Here might be a page title</h1></header><main><p>A paragraph for the main content.</p><p>And another one.</p></main><footer><p>Here's some contact info</p></footer></div>
注意⚠️:v-slot 只能添加在一个 <template> 上。
作用域
为了在 slot 中可以使用外部的数据,可以将数据作为
<span><slot v-bind:user="user">{{ user.lastName }}</slot></span>
动态插槽名
2.6.0 新增
<base-layout><template v-slot:[dynamicSlotName]>...</template></base-layout>
