- 插槽就是子组件中的提供给父组件使用的一个占位符,用<slot></slot> 表示,父组件可以在这个占位符中填充任何模板代码,如 HTML、组件等,填充的内容会替换子组件的<slot></slot>标签,当一个组件有不确定的结构时, 就需要使用 slot 技术。
- 插槽内容是在父组件编译后,再传递给子组件的。
- 作用:让父组件可以向子组件指定位置插入html结构,也是一种组件间通信的方式,适用于 父组件 ===> 子组件 。(父传子)
- 分类:
- 默认插槽
- 具名插槽(父组件填充内容, 父组件通过 v-slot:[name] 或 #[name]的方式指定到对应的插槽中)
- 作用域插槽(描述:作用域插槽其实就是带数据的插槽,即带参数的插槽,简单的来说就是子组件提供给父组件的参数,该参数仅限于插槽中使用,父组件可根据子组件传过来的插槽数据来进行不同的方式展现和填充插槽内容。)(子传父)
举例1.默认插槽和具名插槽
//子组件中
<template>
<div class="header">
<h1>我是页头标题</h1>
<div>
<!--这里存放页头的具体内容-->
<slot name="header"></slot>
</div>
<div class="footer">
<h1>我是页尾标题</h1>
<div>
<!--这里存放页尾的具体内容-->
<slot name="footer"></slot>
</div>
</div>
</div>
</template>
<script>
export default {name: 'ChildModel'}
</script>
//父组件中
<template>
<div>
<div>使用slot分发内容</div>
<div style="margin-top: 30px">
<child-model>
<template v-slot:header>
<h1>我是页头的具体内容</h1>
</template>
<template #footer>
<h1>我是页尾的具体内容</h1>
</template>
</child-model>
</div>
</div>
</template>
<script>
import ChildModel from '@/components/ChildModel.vue'
export default {
name: 'FatherModel',
components: {
ChildModel
}
}
</script>
举例2.作用域插槽
//子组件中
<slot name='section' :list='list'><slot>
data(){
return{
list:[1,2,3]
}
}
//父组件中
<templete #section='type'>
<div>{{type.list}}</div>
</template>