Vue插槽(Slot)的本质是组件间通信的一种方式,具体来说是Vue的内容分发机制。插槽允许开发者在封装组件时,把不确定的、希望由用户指定的部分定义为插槽,可以将其视为组件封装期间为用户预留的内容占位符。插槽的显示与否以及具体如何显示,是由父组件来决定的,而插槽显示的位置则由子组件自身决定。
官方给了一个理解插槽的例子:和avaScript 函数作类比,其概念是类似。
// 父元素传入插槽内容
FancyButton('Click me!')
// FancyButton 在自己的模板中渲染插槽内容
function FancyButton(slotContent) {
return `<button class="fancy-btn">
${slotContent}
</button>`
}
一个概念:父组件模板中的表达式只能访问父组件的作用域;子组件模板中的表达式只能访问子组件的作用域。这和 JavaScript 的词法作用域规则是一致的。
默认内容
<button type="submit">
<slot>
Submit <!-- 默认内容 -->
</slot>
</button>
具名插槽
//父组件中定义插槽的内容
<BaseLayout>
<template v-slot:header>
<!-- header 插槽的内容放这里 -->
</template>
//或
<template #header>
<!-- header 插槽的内容放这里 -->
</template
</BaseLayout>
//子组件中使用插槽的地方写法:
<div class="container">
<header>
<slot name="header"></slot>
</header>
<main>
<slot></slot>
</main>
<footer>
<slot name="footer"></slot>
</footer>
</div>
动态插槽名
<base-layout>
<template v-slot:[dynamicSlotName]>
...
</template>
<!-- 缩写为 -->
<template #[dynamicSlotName]>
...
</template>
</base-layout>
作用域插槽
要同时使用父组件域内和子组件域内的数据,可以像对组件传递 props 那样,向一个插槽的出口上传递 attributes。
//子组件
<!-- <MyComponent> 的模板 -->
<div>
<slot :text="greetingMessage" :count="1"></slot>
</div>
//父组件,默认插槽使用方法
//v-slot="slotProps" 可以类比一个函数签名
<MyComponent v-slot="slotProps">
{{ slotProps.text }} {{ slotProps.count }}
</MyComponent>
//可以在 v-slot 中使用解构:
<MyComponent v-slot="{ text, count }">
{{ text }} {{ count }}
</MyComponent>
具名作用域插槽
<template>
<MyComponent>
<!-- 使用显式的默认插槽 -->
<template #default="{ message }">
<p>{{ message }}</p>
</template>
<template #footer>
<p>Here's some contact info</p>
</template>
</MyComponent>
</template>
作用域插槽使用场景:
//父组件定义具名插槽,子组件专递过来的参数使用解构
<FancyList :api-url="url" :per-page="10">
<template #item="{ body, username, likes }">
<div class="item">
<p>{{ body }}</p>
<p>by {{ username }} | {{ likes }} likes</p>
</div>
</template>
</FancyList>
//子组件FancyList使用插槽
<ul>
<li v-for="item in items">
<slot name="item" v-bind="item"></slot>
</li>
</ul>