单个slot
除非子组件模板包含至少一个 <slot>
插口,否则父组件的内容将会被丢弃。当子组件模板只有一个没有属性的 slot 时,父组件整个内容片段将插入到 slot 所在的 DOM 位置,并替换掉 slot 标签本身。
最初在 <slot>
标签中的任何内容都被视为备用内容。备用内容在子组件的作用域内编译,并且只有在宿主元素为空,且没有要插入的内容时才显示备用内容。
以下代码为 app.vue文件中的代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
<template>
<div id=
"app"
>
<children>
<span>子组件内部元素</span>
</children>
</div>
</template>
<script>
export
default
{
name:
'hello'
,
components: {
children: {
template:
'<div>这里是子组件</div>'
}
}
}
</script>
|
渲染结果为
我们发现写在 children模板内部的span被默认删除了。如果想让span显示那么此刻就应该使用slot。
代码实例:对App.vue的代码做如下修改
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
<template>
<div id=
"app"
>
<children>
<span>子组件内部元素</span>
</children>
</div>
</template>
<script>
export
default
{
name:
'hello'
,
components: {
children: {
template:
'<div><slot><p>默认效果</p></slot>这里是子组件</div>'
}
}
}
</script>
|
那么此时span标签的内容就被渲染出来了。如果在childrem中如果不写span标签那么slot默认会渲染slot里面的内容
具名slot
上面案例中讲解的是当组件的模板中有一个slot的方法,那么一个组件中如果想使用多个slot那么此时就应该使用具名slot。
<slot>
元素可以用一个特殊的属性 name
来配置如何分发内容。多个 slot 可以有不同的名字。具名 slot 将匹配内容片段中有对应 slot
特性的元素。
仍然可以有一个匿名 slot ,它是默认 slot ,作为找不到匹配的内容片段的备用插槽。如果没有默认的 slot ,这些找不到匹配的内容片段将被抛弃。
代码实例:修改App.vue的代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
<template>
<div id=
"app"
>
<children>
<div slot=
"header"
>
<ul>
<li>首页</li>
<li>商城</li>
</ul>
</div>
<div>
这个是默认的没有具名的solt
</div>
<div slot=
"footer"
>
<p>备案号</p>
</div>
</children>
</div>
</template>
<script>
var
Child = {
template:
' <div>这是子组件<div></div> <slot name="header"></slot> <slot></slot> <slot name="footer"></slot> </div>'
}
export
default
{
name:
'hello'
,
components: {
children: Child
}
}
</script>
|
渲染结果为