使用命名插槽
命名的插槽与单个插槽的工作方式类似,但允许你将内容分发到子组件模板中的不同区域。
从前面的示例中获取 page
组件,但修改它的模板,如下所示:
<html>
<head>
<title>Page Title</title>
</head>
<body>
<aside>
<slot name="sidebar"></slot>
</aside>
<main>
<slot name="content"></slot>
</main>
</body>
</html>
使用 page
组件时,我们现在可以通过 slot
属性确定放置内容的位置:
<page>
<p slot="sidebar">This is sidebar content.</p>
<article slot="content"></article>
</page>
结果页面将是:
<html>
<head>
<title>Page Title</title>
</head>
<body>
<aside>
<p>This is sidebar content.</p>
</aside>
<main>
<article></article>
</main>
</body>
</html>
如果定义了 slot
而没有 name
属性,则放置在未指定 slot
属性的组件标记内的任何内容将被放置到该槽中。
请参阅 Vue.js 官方文档中的多插入示例。