目录
插槽slot
普通插槽,具名插槽,作用域插槽
插槽允许我们在调用子组件的时候为子组件传递模板。
<slot> 元素作为承载分发内容的出口。
父级模板里的所有内容都是在父级作用域中编译;子模板里的所有内容都是在子作用域中编译。
在插槽默认模板中,可以直接访问子组件的数据,可以通过props间接访问父组件的数据。
在插槽自定义模板中,可以直接访问父组件的数据,可以通过作用域插槽间接访问子组件的数据。
默认插槽、匿名插槽
如果子组件当中有内容,则显示子组件中的内容;如果子组件当中没有内容,则显示插槽中的内容。
不带 name 的 <slot> 出口会带有隐含的名字“default”
<!-- 如果子组件当中有内容,则显示子组件中的内容 -->
<my-com>hello world</my-com>
<!-- 默认插槽,如果子组件当中没有内容,则显示插槽中的内容 -->
<my-com></my-com>
template: `
<div>
<button><slot name='default'>默认内容</slot></button>
</div>
`
具名插槽
将组件中的内容显示到指定插槽中,用v-slot或#指定插槽填充的位置
<my-com>
<!-- 指定插槽填充位置,自定义插槽模板 -->
<!-- 具名插槽v-slot或#指定插槽填充的位置 -->
<template v-slot:default>
<div>123</div>
</template>
<template v-slot:slot1>
<div>456</div>
</template>
<template #slot1>
<div>789</div>
</template>
</my-com>
template: `
<div>
<button><slot name='default' :subMsg='subMsg'>默认内容</slot></button>
<div>
<slot name='slot1'></slot>