插槽
Vue 实现了一套内容分发的 API,这套 API 的设计灵感源自 [Web Components](https://github.com/WICG/webcomponents/blob/gh-pages/proposals/Slots-Proposal.md) 规范草案,将元素作为承载分发内容的出口。
插槽类型
匿名插槽(默认插槽)
没有命名默认只有一个。
// 子组件<button type="submit"><slot>Submit</slot> // Submit作为默认值</button><submit-button></submit-button> // 渲染出默认值Submit<submit-button>Save // 替换默认值,渲染出Save</submit-button>
具名插槽
与匿名插槽对应,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”。
在向具名插槽提供内容的时候,我们可以在一个 <template> 元素上使用 v-slot 指令,并以 v-slot 的参数的形式提供其名称:
父组件
<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>
作用域插槽
子组件内数据可以被父页面拿到(解决了数据只能从父组件传递到子组件的问题)。
子组件
<span><slot v-bind:user="user">{{ user.lastName }}</slot></span>
父组件
<current-user><template v-slot:default="slotProps"><template scope="slotProps"> // 另一种写法{{ slotProps.user.firstName }}</template></current-user>
