具名插槽
子组件,有多个插槽时,使用name属性指定名称:
<div class="container">
<header>
<slot name="header"></slot>
</header>
<main>
<slot></slot>
</main>
<footer>
<slot name="footer"></slot>
</footer>
</div>
父组件在使用子组件时:
< template >元素中的所有内容都将会被传入相应的插槽。
<base-layout>
<template v-slot:header>
<h1>Here might be a page title</h1>
</template>
<template v-slot:default>
<p>A paragraph for the main content.</p>
<p>And another one.</p>
</template>
<template v-slot:footer>
<p>Here's some contact info</p>
</template>
</base-layout>
渲染出:
<div class="container">
<header>
<h1>Here might be a page title</h1>
</header>
<main>
<p>A paragraph for the main content.</p>
<p>And another one.</p>
</main>
<footer>
<p>Here's some contact info</p>
</footer>
</div>
v-slot 一般只能添加在< template >上
作用域插槽
父级模板里的所有内容都是在父级作用域中编译的,子模板里的所有内容都是在子作用域中编译的。
有时,需要在父级组件中使用子组件的插槽时,访问子组件中的数据
为了让 user数据 在父级的插槽内容中可用,在子组件中,我们可以将user作为< slot >标签的一个attribute绑定上去
<span>
<slot :user="user">
</slot>
</span>
绑定< slot >标签上的attribute被称为插槽prop。
现在在父级作用域中,我们可以使用带值的 v-slot 来定义我们提供的插槽 prop 的名字
<current-user>
<template v-slot:default="slotProps">
{{ slotProps.user.firstName }} // 现在就可以访问到子组件中的user数据了
</template>
</current-user>
// 或者 也可以这样
<current-user>
<template #default="{ user }">
{{ user.firstName }}
</template>
</current-user>
在这个例子中,我们选择将包含所有插槽 prop 的对象命名为 slotProps,但也可以使用任意你喜欢的名字。
具名插槽的缩写
在v-slot:header
中,可以简写为#header
。
Example
子组件
<template>
<div class="ant-pro-footer-toolbar" style="{ width: barWidth, transition: '0.3s all' }">
<div style="float: left"><slot name="extra">{{ extra }}</slot></div>
<div style="float: right"><slot></slot></div>
</div>
</template>
父组件中
<footer-tool-bar>
<a-button type="primary" @click="nextStep" :loading="buttonLoading">下一步</a-button>
</footer-tool-bar>
最后渲染
<div class="ant-pro-footer-toolbar" style="{ width: barWidth, transition: '0.3s all' }">
<div style="float: left;"></div>
<div style="float: right;">
<button type="button" class="ant-btn ant-btn-primary"></button>
</div>
</div>
说明,不指定插槽名字的话,都会到默认插槽中。