- 在默认情况下,向父组件引入的子组件中添加内容,该内容不能被解析
- 在子组件中添加
<slot></slot>
- 可以将该组件中包含的内容解析出来,相当于是在这个组件中的内容会将
<slot></slot>
替代掉
如果子组件中没有该标签,或用作插槽的attbuite 那么从该组件标签的起始到结束标签的内容会被忽略
v-slot
编译作用域
父级模板里的所有内容都是在父级作用域中编译的;子模板里的所有内容都是在子作用域中编译的。
后备内容
插槽的默认值。当未接收到内容时,该内容会被显示
具名插槽
- 给
<slot></slot>
添加一个特殊的属性name
,可以来定义插槽的名字 - 没有定义name属性的标签,name值会默认设置为default
- 在父组件中向具名插槽提供内容的时候,在
<template>
元素中设定一个v-slot
指令,给<template>
标签设置一个name
值,以将这个标签中的内容在name属性值相同的<slot>
标签中显示 - 没有给
template
标签设置v-slot
指令时,会默认放在name值为default的<slot></slot>
中,如果没有符合条件的,则舍弃
// 子组件
<div class="container">
<header>
<slot name="header"></slot>
</header>
<main>
<slot></slot>
</main>
<footer>
<slot name="footer"></slot>
</footer>
</div>
// 父组件
<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>
作用域插槽
- 在子组件中将需要暴露给父组件的属性,绑定到插槽上
- 在父组件中,将内容绑定到指定name的插槽中,给作用域命名
- 在父级模板中
命名.子组件数据对象.属性
调用子组件作用域
子组件
<slot
name="first"
:user="user" 子组件内的数据
>{{ user.name }}</slot>
父组件
<Test01>
<!-- father:{{ msg }} -->
<template v-slot:first="childUser">
插槽名 包含数据的属性名
<h2>这里是子组件的user信息{{ childUser.user.name }}</h2>
</template>
</Test01>
解构插槽
<Test01>
<!-- father:{{ msg }} -->
<!-- user是子组件传过来的数据对象 -->
<template v-slot:first="{ user }">
<h2>这里是子组件的user信息{{ user.age }}</h2>
</template>
</Test01>