插槽的概念
在有些组件的模板中,有一部分区域的内容是比较灵活的,可能需要父组件来指定,如下方代码
<!-- message组件:一个弹窗消息 -->
<div class="message-container">
<div class="content">
<!-- 此位置是消息内容,可以是一个文本,也可能是一段html,需要父组件来指定 -->
</div>
<button>确定</button>
<button>取消</button>
</div>
插槽的简单用法:
在子组件中使用<slot></slot>进行占位,父组件在使用子组件的时候,将需要传递的内容,不论是文本或者是html传递进去,最终,父组件传递的内容会“替换”占位符。
<!-- message组件:一个弹窗消息 -->
<div class="message-container">
<div class="content">
<!-- slot是vue的内置组件 -->
<slot></slot>
</div>
<button>确定</button>
<button>取消</button>
</div>
<!-- 父组件 -->
<Message>
<div class="app-message">
<p>App Message</p>
<a href="">detail</a>
</div>
</Message>
<!-- 最终结果 -->
<div class="message-container">
<div class="content">
<div class="app-message">
<p>App Message</p>
<a href="">detail</a>
</div>
</div>
<button>确定</button>
<button>取消</button>
</div>
具名插槽
如果某个组件中需要父元素传递多个区域的内容,这个组件就需要提供多个插槽。此时,如果像上述简单插槽那样传递内容的时候,这多个插槽不知道该展示在哪个位置。这时,就需要给不同的插槽赋予不同的名字。
<!-- Layout 组件 -->
<div class="layout-container">
<header>
<!-- 页头插槽,名为header -->
<slot name="header"></slot>
</header>
<main>
<!-- 主要内容插槽,名为default -->
<slot></slot>
</main>
<footer>
<!-- 页脚插槽,名为footer -->
<slot name="footer"></slot>
</footer>
</div>
<!-- 父组件 -->
<BaseLayout>
<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 v-slot:default>
<template v-slot:footer> <!--简写为 <template #footer> </template>-->
<p>Here's some contact info</p>
</template>
</BaseLayout>
上述父组件在给默认插槽default传值时,<template>标签可以省略 。