2.4 插槽
1. 插槽内容
插槽可以包含任意的模板代码,包括html,甚至其他组件。
如下:<slot></slot>
在渲染时将被替换成组件<text-document>
之间的所有内容
2. 编译作用域
插槽里插入的内容能访问的作用域
例如下面的 doc.title
就是在访问同级作用域里的内容
完整代码
3. 插槽设置默认内容
如果插槽里没有提供内容,可以设置默认渲染的内容:如下
完整代码
4. 具名插槽
涉及多个插槽时,我们用name的属性来区分各个插槽,没有name属性的默认name属性值为 default,如下:
完整代码
5. 作用域插槽
插槽内如何访问别的作用域下的内容?
如下,要在里用user.firstName来替换默认的user.lastName值,如何在里访问到user呢?vue提供了一套方案,如下:
完整代码链接
单个插槽时的缩写语法和解构赋值语法
// 【原来写法】
<current-user>
<template v-slot:default="slotProps">
{{ slotProps.user.firstName }}
</template>
</current-user>
// 【缩写语法】
<current-user v-slot="slotProps">
{{ slotProps.user.firstName }}
</current-user>
// 【也可用ES5的解构赋值语法】
<current-user v-slot="{ user }">
{{ user.firstName }}
</current-user>
6. Dynamic Slot Names
插槽名可以是动态的
<base-layout>
<template v-slot:[dynamicSlotName]>
...
</template>
</base-layout>
7. 具名插槽的缩写
用#代替v-slot:
<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>
更多Vue文档解读:《Vue Doc 笔记》
(完)