插槽内容与出口
在之前的章节中,我们已经了解到组件能够接收任意类型的 JavaScript 值作为 props,但组件要如何接收模板内容呢?在某些场景中,我们可能想要为子组件传递一些模板片段,让子组件在它们的组件中渲染这些片段。
举例来说,这里有一个 <FancyButton>
组件,可以像这样使用:
<FancyButton>Click me! <!-- 插槽内容 -->
</FancyButton>
而 <FancyButton>
的模板是这样的:
<button class="fancy-btn"><slot></slot> <!-- 插槽出口 -->
</button>
<slot>
元素是一个插槽出口 (slot outlet),标示了父元素提供的插槽内容 (slot content) 将在哪里被渲染。
<button class="fancy-btn">Click me!</button>
通过使用插槽,<FancyButton>
仅负责渲染外层的 <button>
(以及相应的样式),而其内部的内容由父组件提供。
理解插槽的另一种方式是和下面的 JavaScript 函数作类比,其概念是类似的:
// 父元素传入插槽内容
FancyButton('Click me!')// FancyButton 在自己的模板中渲染插槽内容
function FancyButton(slotContent) {return `<button class="fancy-btn">${slotContent}</button>`
}
<FancyButton><span style="color:red">Click me!</span><AwesomeIcon name="plus" />
</FancyButton>
通过使用插槽,<FancyButton>
组件更加灵活和具有可复用性。现在组件可以用在不同的地方渲染各异的内容,但同时还保证都具有相同的样式。