1. 组件插槽的作用
父组件向 子组件 传递内容:
- 不是之前的数据传递,是模板数据的传递
我们平常定义的 组件模板,渲染到页面上是这样的:
比如: 我们的组件模板为 a.vue
要渲染在 b.vue
上,就是这样的:
a.vue
<template>
我是子组件,要渲染到 b.vue 身上的
</template>
a.vue 导入到 b.vue 上;
b.vue
<template>
<!-- 子组件的占位符 -->
<a组件></a组件>
</template>
<script>
import a组件 from './component/a.vue'
export default {
components: {
a组件
}
}
</script>
在 b.vue 中的 子组件占位符 上写内容,在页面上是显示不了的,会被 a.vue 的内容覆盖掉;
b.vue:
<template>
<!-- 在 b.vue 上显示不了 -->
<a组件>我是文字</a组件>
</template>
使用组件的插槽功能,可以将 父组件 的元素 填到 子组件 中使用 slot
标签来占位的地方;
a.vue:
<template>
我是子组件,要渲染到 b.vue 身上的
<!-- 相当一个占位符,可以接收 父组件 中写在 子组件标签中的 内容; -->
<slot></slot>
</template>
2. 具名插槽
定义:
有时我们需要多个插槽,为了 区分多个插槽,我们可以给 插槽 起名字,这叫做 “具名插槽” 。
主要代码:
父
<template>
<div>
<子组件>
<template v-slot:a> a </template>
<template v-slot:b> b </template>
<template v-slot:c> c </template>
</子组件>
</div>
</template>
子
<template