Vue3 具名插槽使用指南:详细解析与简写语法
Vue3 的具名插槽使用方法与 Vue2 略有不同。以下是 Vue3 中具名插槽的基本使用方法:
- 在父组件中定义具名插槽
<template>
<div>
<slot name='header'></slot>
<slot></slot>
<slot name='footer'></slot>
</div>
</template>
- 在子组件中使用具名插槽
<template>
<div>
<template v-slot:header>
<h1>这是头部</h1>
</template>
<p>这是主体</p>
<template v-slot:footer>
<p>这是底部</p>
</template>
</div>
</template>
注意,在 Vue3 中使用具名插槽的语法有一些变化,使用v-slot指令来替代 Vue2 中的slot-scope。具名插槽需要在v-slot指令中指定插槽的名称,如v-slot:header。
- 简写语法
Vue3 还提供了一种简写语法,可以使用#来代替v-slot。例如:
<template>
<div>
<#header>
<h1>这是头部</h1>
</#header>
<p>这是主体</p>
<#footer>
<p>这是底部</p>
</#footer>
</div>
</template>
这样可以更加简洁地定义具名插槽。
除了具名插槽,Vue3 还引入了新的插槽类型——作用域插槽(Scoped Slots)。作用域插槽可以让父组件向子组件传递数据,这个在 Vue2 中也有,但是 Vue3 的写法和 Vue2 有所不同,需要注意。
原文地址: https://www.cveoy.top/t/topic/mLmc 著作权归作者所有。请勿转载和采集!