动态组件

动态组件指的是动态切换组件的显示与隐藏。

实现动态组件渲染

vue提供了一个内置的<component>组件,专门用来实现动态组件的渲染。

示例代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<script>
// 1.当前要渲染的组件名称
return {
comNmae: 'Left'
}
</script>

<template>
// 2.通过is属性,动态指定要渲染的组件
<component :is="comName"></component>

// 3.点击按钮,动态切换组件的名称
<button @click="comNmae = 'Left'"> 展示Left组件 </button>
<button @click="comNmae = 'Right'"> 展示Right组件 </button>
</template>

使用keep-alive保持状态

默认情况下,切换动态组件时无法保持组件的状态。

此时可以使用vue内置的<keep-alive>组件保持动态组件的状态。

示例代码:

1
2
3
4
5
<template>
<keep-alive>
<component :is="comName"></component>
</keep-alive>
</template>

插槽

插槽(Slot)是vue为组件的封装者提供的能力。

允许开发者在封装组件时,把不确定、希望由用户指定的部分定义为插槽。

基础用法

在封装组件时,可以通过<slot>元素定义插槽,从而为用户预留内容占位符。

示例代码:

1
2
3
4
5
6
<template>
<p> 这是 MyCom1 组件的第1个 p 标签 </p>
<!-- 通过slot标签,为用户预留内容占位符(插槽)-->
<slot></slot>
<p> 这是 MyCom1 组件的最后一个 p 标签 </p>
</template>
1
2
3
<my-com-1>
<p>---用户自定义的内容---</p>
</my-com-1>

后备内容

后备内容,也叫做默认内容。封装组件时,可以为slot插槽提供后备内容。

1
2
3
4
5
6
<template>
<p> 这是 MyCom1 组件的第1个 p 标签 </p>
<!-- 通过slot标签,为用户预留内容占位符(插槽)-->
<slot> 后备内容 </slot>
<p> 这是 MyCom1 组件的最后一个 p 标签 </p>
</template>

具名插槽

如果在封装组件时需要预留多个插槽节点,则需要为每个<slot>插槽指定具体的name名称。

这种带有具体名称的插槽叫做”具名插槽“,使用v-slot为具名插槽提供内容。

v-slot可以简写为#,如:v-slot:header 和 #header 是等价的。

示例代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<div class="container">
<header>
<!-- 我们希望把页头放在这里 -->
<slot name="header"></slot>
</header>

<main>
<!-- 我们希望把主要内容放这里 -->
<slot></slot>
</main>

<footer>
<!-- 我们希望把页脚放这里 -->
<slot name="footer"></slot>
</footer>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
<my-com-2>
<template v-slot:header>
<h1>滕王阁序</h1>
</template>

<template v-slot:default>
<p>豫章故郡,洪都新府。</p>
</template>

<template v-slot:footer>
<p>落款:王勃</p>
</template>
</my-com-2>

作用域插槽

封装组件的过程中,可以为预留<slot>插槽绑定props数据。

这种带有props数据的<slot>叫做作用域插槽。

1
2
3
4
<template>
<tbody>
<slot :scope="test"></slot>
</template>
1
2
3
4
5
6
7
<my-com-3>
<template v-slot:default="scope">
<tr>
<td> {{ scope }} </td>
</tr>
</template>
</my-com-3>