VuePress 實現(xiàn)了一套針對 Markdown 的內(nèi)容分發(fā) API。通過這個特性,你可以將你的文檔分割成多個片段,以便于在布局組件中靈活組合。
為什么需要 Markdown 插槽
Markdown 文件是元數(shù)據(jù)(頁面內(nèi)容、配置等)的提供者,而布局組件負責消費他們。我們可以通過 frontmatter 來定義一些普通數(shù)據(jù)類型的元數(shù)據(jù),但對于 Markdown / HTML 這種涉及到編譯前后差異的復雜元數(shù)據(jù),frontmatter 卻無能能力。
Markdown 插槽便解決了這一類問題。
具名插槽
你可以通過下述的語法來定義一個具名 Markdown 插槽:
::: slot name
:::
在布局組件中利用 Content 組件來使用該插槽:
<Content slot-key="name"/>
提示
這里我們使用的是 slot-key 而不是 slot,這是因為在 Vue 中,slot 是一個保留的 prop 名。
插槽的默認內(nèi)容
默認情況下,一個 Markdown 文件中的普通內(nèi)容將會成為 Markdown 插槽的默認內(nèi)容,你可以直接使用 Content 組件來訪問它:
<Content/>
例子
假設你的布局組件如下:
<template>
<div class="container">
<header>
<Content slot-key="header"/>
</header>
<main>
<Content/>
</main>
<footer>
<Content slot-key="footer"/>
</footer>
</div>
</template>
如果一個頁面的 markdown 的內(nèi)容是這樣:
::: slot header
# Here might be a page title
:::
- A Paragraph
- Another Paragraph
::: slot footer
Here's some contact info
:::
那么這一頁最終被渲染出的 HTML 將會是:
<div class="container">
<header>
<div class="content header">
<h1>Here might be a page title</h1>
</div>
</header>
<main>
<div class="content default">
<ul>
<li>A Paragraph</li>
<li>Another Paragraph</li>
</ul>
</div>
</main>
<footer>
<div class="content footer">
<p>Here's some contact info</p>
</div>
</footer>
</div>
請注意:
- 和 Vue 本身提供的 slot 機制不太相同,每個 Content 分發(fā)的內(nèi)容都會被一個 div 所包裹,其 class 是 content 和 slot 的名字。
- 請確保所定義的 slot 的唯一性。