插槽
官方文档:传送门
默认插槽
- 当子组件中未使用
<slot></slot>
标签时,父组件内<Child></Child>
标签间的内容会被忽略 - 反之,父组件内
<Child></Child>
标签间的内容会替换<slot></slot>
<slot></slot>
标签之间可以存在内容,当父组件的<Child></Child>
标签间没有内容时,就会默认显示 ` 标签之间的内容
// parent
...
<Child>
<div>内容...</div>
<p>内容...</p>
</Child>
...
// child
...
<p><slot>默认显示...</slot></p>
...
具名插槽
- 具名插槽的出现是为了解决一种更复杂的场景:当子组件中需要存在多个
<slot></slot>
标签时
// child
...
<header>
<!-- 这里放头部的内容 -->
<slot name="header"></slot>
</header>
<main>
<!-- 这里放主要的内容 -->
<slot name="main"></slot>
</main>
<footer>
<!-- 我们希望把页脚放这里 -->
<slot name="footer"></slot>
</footer>
...
// parent
<Child>
<template v-slot="header">头部内容...</template>
<template v-slot="main">主要内容...</template>
<template v-slot="footer">页脚内容...</template>
</Child>
注意:只有默认插槽的情况下可以
<Child v-slot:default></Child>
,其余状态下 v-slot 都只能在 template 标签上
作用域插槽
目的是为了使
<Child></Child>
间的内容可以访问到子组件的变量或方法
- 在
<slot></slot>
标签上绑定属性,插槽中的内容即可通过v-slot:插槽名="定义一个变量"
的形式获取包含<slot></slot>
上所有属性的对象 - 默认插槽的插槽名是
default
// parent
<Child>
<template v-slot:default="slotProps">
{{ slotProps.user }}
</template>
<template v-slot:other="otherSlotProps">
{{ otherSlotProps.foo }}
</template>
</Child>
// child
...
<slot :user="user"></slot>
<slot :foo="foo"></slot>
...