父级模板里的所有内容都是在父级作用域中编译的;子模板里的所有内容都是在子作用域中编译的。
1.基本使用
A组件 //navigation-link
<div> <slot></slot> </div>
B组件 <navigation-link>传 html, 组件 , 模板代码</navigation-link>
- 插槽具有默认值
A组件 //navigation-link
<button type="submit"> <slot>Submit</slot> </butto>
B组件
<navigation-link></navigation-link> // 不传值 默认显示Submit
3.具名插槽
//A组件 // base-layout
<div class="container">
<header>
<!-- 我们希望把页头放这里 -->
</header>
<main>
<!-- 我们希望把主要内容放这里 -->
</main>
<footer>
<!-- 我们希望把页脚放这里 -->
</footer>
</div>
//B组件 v-slot:xxx 只能写在template里面 / slot = xxx 可以直接写在html标签里面或者 template
<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 slot="header">
<h1>Here might be a page title</h1>
</template>
// 或者 直接在标签里面
<h1 slot="header">Here might be a page title</h1>
4 作用域插槽
// 子组件 的属性 能被父组件使用
子组件 //使用v-bind
<span>
<slot v-bind:user="user">
{{ user.lastName }}
</slot>
</span>
父组件 //使用 //slotProps 的命名 随意 :default 可以省略
<current-user>
<template v-slot:default="slotProps">
{{ slotProps.user.firstName }}
</template>
</current-user>
--------------------------------------------------------
// 类似 element 表格数据 自动排序$index 是 element表格的一个属性
<el-table-column label="序号">
<template v-slot="scope">
{{(page - 1) * size + scope.$index + 1}}
</template>
</el-table-column>
--------------------------------------------------------
// 多个插槽需使用完整语法
<current-user>
<template v-slot:default="slotProps">
{{ slotProps.user.firstName }}
</template>
<template v-slot:other="otherSlotProps">
...
</template>
</current-user>
// 可以使用 解构语法
<current-user v-slot="{ user }">
{{ user.firstName }}
</current-user>
<current-user v-slot="{ user: person }">
{{ person.firstName }}
</current-user>
<current-user v-slot="{ user = { firstName: 'Guest' } }"> // 插槽有默认值
{{ user.firstName }}
</current-user>
跟 v-on 和 v-bind 一样,v-slot 也有缩写,即把参数之前的所有内容 (v-slot:) 替换为字符 #。例如 v-slot:header 可以被重写为 #header:
<base-layout>
<template #header>
<h1>Here might be a page title</h1>
</template>
<p>A paragraph for the main content.</p>
<p>And another one.</p>
<template #footer>
<p>Here's some contact info</p>
</template>
</base-layout>
然而,和其它指令一样,该缩写只在其有参数的时候才可用。这意味着以下语法是无效的:
<!-- 这样会触发一个警告 -->
<current-user #="{ user }">
{{ user.firstName }}
</current-user>
如果你希望使用缩写的话,你必须始终以明确插槽名取而代之:
<current-user #default="{ user }">
{{ user.firstName }}
</current-user>