有时我们需要多个插槽。例如对于一个带有如下模板的组件:
<div class="modal" v-if="visible">
<div class="modal-content">
<header>
<!-- 我们希望把页头放这里 -->
</header>
<main>
<!-- 我们希望把主要内容放这里 -->
</main>
<footer>
<!-- 我们希望把页脚放这里 -->
</footer>
</div>
</div>
对于这样的情况,slot元素有一个特殊的属性:name。这个属性可以用来定义额外的插槽:
<div class="modal" v-if="visible">
<div class="modal-content">
<header>
<slot name="header"></slot>
</header>
<main>
<slot></slot>
</main>
<footer>
<slot name="footer"></slot>
</footer>
</div>
</div>
没有写 name 属性的情况下,其实它会自动带隐含的名字“default”,也就是所说的“匿名插槽”。
带有 name 属性的插槽,我们称为“具名插槽”。
在向具名插槽提供内容的时候,我们可以在一个 template 元素上使用 v-slot 指令,并以 v-slot 的参数的形式提供其名称:
<Modal :visible.sync="visible">
<template v-slot:header>
<h1>Modal title</h1>
</template>
<div>main content</div>
<div>main content</div>
<template v-slot:footer>
<p>Modal footer</p>
</template>
</Modal>
弹窗组件:
父App.vue
<template>
<div id="app">
<button @click="visible = true" class="btn">打开“协议”弹框</button>
<button @click="visibleApply = true" class="btn">打开“成为大牛”弹框</button>
<!-- “协议”弹框 -->
<Modal
customClassName="agreement-modal"
title="用户协议"
:visible.sync="visible"
@confirm="confirm"
>
<template>
<div class="hignlight">欢迎来到XXX!</div>
<div class="content">
请您仔细阅读以下条款,如果您对本使用须知的任何条款表示异议,您可以选择不进入,此用户协议范围包含产品。用户注册成功后,将给每个用户一个用户帐号,该用户帐号由用户负责保管;用户应