插槽一般组件用的比较多吧,方几个预留的位置让用户想放啥东西就放啥东西,不放也没事。
首先是最简单的
一、匿名插槽
子组件child
<div>
创建组件的插槽
<slot></slot>
</div>
父组件
项child组件中插入一个哇
<child>哇</child>
最后呈现的自组件的样子
<div>哇</div>
二、具名插槽
1、旧语法(Vue2.6.0之前)
子组件child
<div>
<slot></slot>
<slot name="想要取的插槽名字"></slot>
</div>
父组件
项child组件中插入
<child>
默认插槽中的内容
<template slot="想要取的插槽名字">
具名插槽中插入的内容
</template>
</child>
也可以写成这样
项child组件中插入
<child>
默认插槽的名字是default
<template slot="default">
默认插槽中的内容
</template>
<template slot="想要取的插槽名字">
具名插槽中插入的内容
</template>
</child>
最后出来是
<child>
默认插槽中的内容 具名插槽中插入的内容
</child>
1、新语法(Vue2.6.0之及之后)
子组件的插槽定义不变
父组件使用插槽
项child组件中插入
<child>
默认插槽的名字是default
<template v-slot:default>
默认插槽中的内容
</template>
<template v-slot:想要取的插槽名字>
具名插槽中插入的内容
</template>
</child>
1、插槽的默认内容
子组件child
<div>
<slot>哇</slot>
</div>
如果父组件
项child组件中插入
<child>
哇哦
</child>
则最终
<div>哇哦</div>
如果父组件
<child></child>
则
<div>哇</div>
三、作用域插槽
1、旧语法(Vue2.6.0之前)
子组件child
自组件有孩子的所有信息child对象,然后把这个对象传给调用的父组件
<div>
<slot :child="child"></slot>
</div>
父组件想拿到孩子的名字然后填上去
<child>
<template slot="default" slot-scope="slotProps">
{{slotProps.child.name}}
</template>
</child>
或者其他各个元素上都可以使用
<child>
<p slot="default" slot-scope="slotProps">
{{slotProps.child.name}}
</p>
</child>
解构
<child>
<p slot="default" slot-scope="{child}">
{{child.name}}
</p>
</child>
1、新语法(Vue2.6.0之及之后)
<div>
<slot :child="child"></slot>
</div>
父组件想拿到孩子的名字然后填上去
<child>
改成了v-slot后面是名称等于后面是值
<template v-slot:default="slotProps">
{{slotProps.child.name}}
</template>
</child>
还可以缩写默认插槽
<child>
改成了v-slot后面是名称等于后面是值
<template v-slot="slotProps">
{{slotProps.child.name}}
</template>
</child>
解构重命名
<child>
<template v-slot="{child:haizi}">
{{haizi.name}}
</template>
</child>
也可以动态填写插槽名
<child>
<template v-slot:[asdada]="{child:haizi}">
{{haizi.name}}
</template>
</child>
缩写
<child>
<template #[asdada]="{child:haizi}">
{{haizi.name}}
</template>
</child>