解决什么痛点
父子组件传参可以用用Props来完成,但父组件如何给子组件传一个template,即模块片段呢?这时候就要用到slot,即需要给子组件的内容,在父组件中定义好,即叫插槽的出口,然后在子组件设定好插入的位置即slot插槽的位置,又叫插槽的入口。当父组件中没有需要给子组件插槽插入信息时,显示的是子组件插槽定义的默认信息。
用法1:父子组件传模板的内容,没有内容时显示缺省的内容
// 子组件Catagory.vue
<template>
<div class="category">
<h3>{{title}}分类</h3>
<slot>没有内容 </slot>
</div>
</templage>
// 父组件 App.vue
<template>
<div class="containter">
<Category title="美食">
<img src="https://www.test.com/1.jpg" alt="" srcset="">
</Category>
<Category title="电影">
<video controls src="https://www.test.com/1.mp4"></video>
</Category>
</div>
</template>
用法2:具名式slot,父组件把内容放入子组件的哪一个slot插槽中。
// 子组件
<div class="container">
<header>
<slot name="header"></slot>
</header>
<main>
<slot></slot>
</main>
<footer>
<slot name="footer"></slot>
</footer>
</div>
// 父组件,#header就是v-slot:header简写法。
<BaseLayout>
<template #header>
<h1>Here might be a page title</h1>
</template>
<template #default>
<p>A paragraph for the main content.</p>
<p>And another one.</p>
</template>
<template #footer>
<p>Here's some contact info</p>
</template>
</BaseLayout>
用法3:作用域插槽,父组件获取到子组件的参数,即某些场景下插槽的内容可能想要同时使用父组件域内和子组件域内的数据。
// 父组件
<MyComponent v-slot="slotProps">
{{ slotProps.text }} {{ slotProps.count }}
</MyComponent>
或者
<MyComponent v-slot="{ text, count }">
{{ text }} {{ count }}
</MyComponent>
// 子组件
<!-- <MyComponent> 的模板 -->
<div>
<slot :text="greetingMessage" :count="1"></slot>
</div>