具名插槽
需要多个插槽的情况,slot 元素有一个特殊的属性:name,用来定义额外的插槽。一个不带 name 的 <slot> 出口会带有隐含的名字“default”。
在向具名插槽提供内容的时候,我们可以在一个 <template> 元素上使用 v-slot 指令,并以 v-slot 的参数的形式提供其名称:
<template v-slot:footer>
<p>展示</p>
</template>复制代码
代码
父组件
<template>
<div>
<About>
<template v-slot:header="slotProps">
<h1>{{slotProps.header + ' ' + msg}}</h1>
</template>
<p>这是没有命名的slot</p>
<p>这是没有命名的slot2</p>
<template v-slot:footer>
<p>v-slot:footer</p>
</template>
</About>
</div>
</template>
<script>
import About from './About.vue'
export default {
data() {
return {
msg: '这是根组件的消息msg'
}
},
components: {
About
}
}
</script>
复制代码
子组件
<template>
<div>
<header>
<slot name="header" :header="header"></slot> //header是要传入父组件插槽中的值
</header>
<slot></slot>
<footer>
<slot name="footer"></slot>
</footer>
</div>
</template>
<script>
export default {
data() {
return {
header: '来自子组件的头部消息header'
}
}
}
</script>复制代码
渲染结果如下
总结
1、组件中可以使用template标签,加v-slot指令制定具名插槽,当没有指定插槽name时,默认出口会带有隐含的名字“default”。
2、根组件可以利用
2、根组件可以利用
v-slot:header="slotProps"
接受组件中的消息,组件中只需要在
<slot name="header" :header="header"></slot>
就可以了
<about v-slot="slotProps">
4、动态参数也可是使用到插槽当中,例如:
pro: 'header'
,
<template v-slot:[pro]='solt'>nihao {{solt.header}}</template>
,代表name属性是header的插槽
5、v-slot的缩写是#,但是如果使用#的话,必须始终使用具插槽来代替
<about #default="slotProps">