1、定义
插槽就是子组件中的提供给父组件使用的一个占位符,父组件可以在这个占位符中填充任何模板代码,如 HTML、组件等,填充的内容会替换子组件的标签。插槽显不显示、怎样显示是由父组件来控制的,而插槽在哪里显示就由子组件来进行控制
2、基础插槽
// 父组件
<template>
<div>
<helloWorld >
<div>插槽信息1</div>
<div>插槽信息2</div>
</helloWorld>
</div>
</template>
// 子组件
<template>
<div class="hello">
<h1>子组件内容</h1>
<slot>默认内容</slot>
</div>
</template>
在子组件中添加slot标签进行占位,将父组件中内容补充进去,只要存在组件标签内的都可以展示。如果没有预留插槽的内容将会被丢弃。
当组件没有提供内容时就会显示 插槽内的 默认内容
3、具名插槽
在封装组件时需要预留多个插槽节点,就需要为每个slot指定具体的name名称。
// 父组件
<template>
<div>
<helloWorld >
<template v-slot:test1><div>789</div></template>
<template #test2><div>7890</div></template> // 简写使用 #
</helloWorld>
</div>
</template>
// 子组件
<template>
<div class="hello">
<h1>子组件内容</h1>
<slot name="test1"></slot>
<slot name="test2"></slot>
</div>
</template>
注:
- 父组件中指定的插槽名字再子组件中不存在,则传递的信息将不会展示
- 子组件中的插槽名没有在父组件中有数据补充的话,也将直接弃用
- 如果子组件有多个默认插槽,而父组件所有指定到默认插槽的填充内容,将会且全都填充到子组件的每个默认插槽中。
4、作用域插槽
在封装组件的过程中,子组件为预留的插槽提供数据,直接在父组件的插槽中使用。
// 父组件
<template>
<div>
<helloWorld >
<template slot-scope="hello"> // 也可以使用v-slot: 或者# 号来获取数据
<div v-for="item in hello.data" :key="item">{{item}}</div>
</template>
</helloWorld>
</div>
</template>
// 子组件
<template>
<div class="hello">
<h1>子组件内容</h1>
<slot :data="data"></slot>
</div>
</template>
<script>
export default {
name: 'helloWorld',
data(){
return{
data:[1,2,3,4,5,6]
}
}
}
</script>