什么是插槽
插槽就是子组件中的提供给父组件使用的一个占位符,用<slot></slot> 表示,父组件可以在这个占位符中填充任何模板代码,如 HTML、组件等,填充的内容会替换子组件的<slot></slot>标签。
代码如下:
一、匿名插槽
1、在子组件中放一个占位符
<template>
<div>
<h1>今天天气状况:</h1>
<slot></slot>
</div>
</template>
<script>
export default {
name: 'child'
}
</script>
2、在父组件中给这个占位符填充内容
<template>
<div>
<div>使用slot分发内容</div>
<div>
<child>
<div style="margin-top: 30px">多云,最高气温34度,最低气温28度,微风</div>
</child>
</div>
</div>
</template>
<script>
import child from "./child.vue";
export default {
name: 'father',
components:{
child
}
}
</script>
二、具名插槽
描述:具名插槽其实就是给插槽取个名字。一个子组件可以放多个插槽,而且可以放在不同的地方,而父组件填充内容时,可以根据这个名字把内容填充到对应插槽中。
1、子组件的代码,设置了两个插槽(header和footer):
<template>
<div>
<div class="header">
<h1>我是页头标题</h1>
<div>
<slot name="header"></slot>
</div>
</div>
<div class="footer">
<h1>我是页尾标题</h1>
<div>
<slot name="footer"></slot>
</div>
</div>
</div>
</template>
2、父组件填充内容, 父组件通过 v-slot:[name] 的方式指定到对应的插槽中
<template>
<div>
<div>slot内容分发</div>
<child1>
<template slot="header">
<p>我是页头的具体内容</p>
</template>
<template slot="footer">
<p>我是页尾的具体内容</p>
</template>
</child1>
</div>
</template>
<script>
import child1 from "./child1.vue";
export default {
name: "father1",
components: {
child1
}
}
三、作用域插槽
1.定义一个子组件,有个具名插槽son,并且通过属性绑定子组件的数据user。
const sonCom = {
template: `
<div>
<slot name="son" :user="user">子组件数据:{{user.firstName}}</slot>
</div>
`,
data() {
return {
user: {
firstName: '三',
lastName: '张'
}
}
}
}
2.父组件调用子组件时,假设不想展示firstName了,想展示lastName。
<div id="app">
<son-com v-slot:son="scope">{{scope.user.lastName}}</son-com>
</div>









