具名插槽有时我们需要多个插槽。例如对于一个带有如下模板的 base-layout 组件:div class=containerheader!-- 我们希望把页头放这里 --/headermain!-- 我们希望把主要内容放这里 --/mainfoote...

具名插槽
有时我们需要多个插槽。例如对于一个带有如下模板的 <base-layout>
组件:
<div class="container">
<header>
<!-- 我们希望把页头放这里 -->
</header>
<main>
<!-- 我们希望把主要内容放这里 -->
</main>
<footer>
<!-- 我们希望把页脚放这里 -->
</footer>
</div>
对于这样的情况,<slot>
元素有一个特殊的 attribute:name
。这个 attribute 可以用来定义额外的插槽:
<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>
现在 <template>
元素中的所有内容都将会被传入相应的插槽。任何没有被包裹在带有 v-slot
的 <template>
中的内容都会被视为默认插槽的内容。
然而,如果你希望更明确一些,仍然可以在一个 <template>
中包裹默认插槽的内容:
<base-layout>
<template v-slot:header>
<h1>Here might be a page title</h1>
</template>
<template v-slot:default>
<p>A paragraph for the main content.</p>
<p>And another one.</p>
</template>
<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
attribute 不同。
本文标题为:Vue中具名插槽


基础教程推荐
- 解决:layUI数据表格+简单查询 2022-12-16
- 在IE中为abbr标签加样式 2022-10-16
- Ajax提交表单并接收json实例代码 2023-02-13
- AJax 把拿到的后台数据在页面中渲染的实例 2023-02-22
- JavaScript垃圾回收机制(引用计数,标记清除,性能优 2022-08-31
- ajax实现数据分页查询 2023-01-31
- 原生ajax瀑布流demo分享(必看篇) 2023-02-01
- 关于ajax异步访问数据的问题 2023-02-23
- Unicode中的常用字母小结 2022-09-21
- 纯javascript的ajax实现php异步提交表单的简单实例 2022-12-28