v-slot
缩写:
#参数:插槽名 (可选,默认值是
default)
一、具名插槽
子组件模板
<div class="container">
<header>
<!-- header 是插槽名,是v-slot后面的名称,没写的默认default -->
<slot name="header"></slot>
</header>
<main>
<slot></slot>
</main>
<footer>
<slot name="footer"></slot>
</footer>
</div>
一个不带 name 的 <slot> 出口会带有隐含的名字“default”。
使用模板
<base-layout>
<template v-slot:header>
<h1>这是一个插入的头模板</h1>
</template>
<p>这是default插入的模板</p>
<template v-slot:footer>
<h2>这是一个插入的尾模板</h2>
</template>
</base-layout>
效果:
二、作用域插槽
有时让插槽内容能够访问子组件中才有的数据是很有用的。例如,设想一个带有如下模板的 <current-user> 组件
<span>
<slot>{{ user.lastName }}</slot>
</span>
我们可能想换掉备用内容,用名而非姓来显示。如下:
<current-user>
{{ user.firstName }}
</current-user>
然而上述代码不会正常工作,因为只有 <current-user> 组件可以访问到 user 而我们提供的内容是在父级渲染的,在父级组件上使用user是访问不到数据的。
为了让 user 在父级的插槽内容中可用,我们可以将 user 作为 <slot> 元素的一个属性绑定上去:
<span>
<slot :user="user">
{{ user.lastName }}
</slot>
</span>
<current-user>
<!-- slotProps 这个名字可以改成你喜欢的 -->
<template #default="slotProps">
{{ slotProps.user.firstName }}
</template>
</current-user>