刚做完一个项目,被库里的各种插槽搞的头疼,今天专门总结一下各种写法,不涉及原理。
1.匿名插槽
子组件 test.vue
<div>
<h3>插槽</h3>
<slot></slot>
<slot>当没有使用插槽时,这里可以放置默认内容</slot>
<slot name="text"></slot>
</div>
父组件 App.vue
<Test>
<p>hello</p>
</Test>
注意
:多个匿名插槽 默认会将子组件标签中的内容全部渲染到每个匿名插槽
2.具名插槽
子组件 test.vue
<div>
<h3>插槽</h3>
<slot name="text"></slot>
</div>
具名插槽的四种写法
<Test>
写法1
<p slot="text">具名插槽1</p>
写法2
<template slot="text">
<p>具名插槽2</p>
</template>
写法3
<template v-slot:text>
<p>具名插槽3</p>
</template>
写法4
<template #text>
<p>具名插槽4</p>
</template>
</Test>
3.作用域插槽
子组件 test.vue
<div>
<h3>插槽</h3>
<slot name="text" :row="'作用域插槽'"></slot>
</div>
父组件
<Test>
写法1
<template v-slot:text="data">
<div>{{ data.row }}</div>
</template>
写法2
<template #text="{row}">
<div>{{ row }}</div>
</template>
写法3
<template slot="text" slot-scope="data">
<div>{{ data.row }}</div>
</template>
</Test>
需要注意的是,虽然在所有的 2.x 版本中 slot
和 slot-scope
仍被支持。但实际上已经被官方废弃且不会出现在 Vue 3 ,所以这里更推荐小伙伴们使用v-slot
替代slot
和 slot-scope
指令。
详情请参考官方文档