slot 插槽
定义: slot 是父组件与子组件之间的通信方式,可以将父组件的内容显示在子组件当中。
例:
有一个组件
<say-to> 你有口罩吗?</say-to>
在组件的模板中写为:
<div>你好,<slot></slot></div>
当组件渲染时,<slot></slot> 会被替换为“你有口罩吗?”
- 插槽内可以包含任何模板代码,包括 HTML甚至是其他组件
- 如果
<say-to>没有包含一个<slot>元素,则该组件起始标签和结束标签之间的任何内容都会被抛弃。
插槽的后备内容
有时为一个插槽设置具体的后备 (也就是默认的) 内容是很有用的,它只会在没有提供内容的时候被渲染
<slot>组件没有提供内容时,这里的内容将会渲染。反之则不会</slot>
具名插槽
在需要使用的多个插槽的情况下,例如:
<div class="container">
<header>
<!-- 我们希望把页头放这里 -->
</header>
<main>
<!-- 我们希望把主要内容放这里 -->
</main>
<footer>
<!-- 我们希望把页脚放这里 -->
</footer>
</div>
可以使用 slot 的 name 属性:
<div class="container">
<header>
<slot name="header"></slot>
</header>
<main>
<slot></slot>
</main>
<footer>
<slot name="footer"></slot>
</footer>
</div>
在向具名插槽提供内容时,需要在一个 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 中包裹默认插槽的内容:
<template v-slot:default>
<p>A paragraph for the main content.</p>
<p>And another one.</p>
</template>
注意: v-slot 只能添加在 <template> 上
- 具名插槽的缩写:
跟v-on和v-bind一样,v-slot也有缩写,即把参数之前的所有内容 (v-slot:) 替换为字符#。例如v-slot:header可以被重写为#header
在动态组件上使用:keep-alive
在一个多标签的界面中使用 is 属性来切换不同的组件:
<component v-bind:is="currentTabComponent"></component>
当在这些组件之间切换的时候,有时会想保持这些组件的状态,以避免反复重渲染导致的性能问题。希望那些标签的组件实例能够被在它们第一次被创建的时候缓存下来。为了解决这个问题,可以用一个 <keep-alive> 元素将其动态组件包裹起来。
<!-- 失活的组件将会被缓存!-->
<keep-alive>
<component v-bind:is="currentTabComponent"></component>
</keep-alive>
注意:这个<keep-alive> 要求被切换到的组件都有自己的名字,不论是通过组件的 name 选项还是局部/全局注册。