目录
插槽 slot 在实际的项目开发中是经常使用的,主要分为三大类:默认插槽、具名插槽和作用域插槽,也是比较容易上手的。
一、插槽的含义
插槽 slot 是写在子组件的代码中,供父组件使用的占位符。在代码中,大致写为如下的形式,后面会进行详细的写法介绍。
<slot> </slot>
插槽其实就是在写 slot 的地方挖个坑,等着组件的使用者,即父组件,进行填充。子组件中使用插槽 slot 后,父组件可以在这个占位符中填充内容,包括数据、html代码、组件等,也就是说,当子组件的某部分内容是根父组件填充的不同而变化的,那我们就可以使用插槽slot,具体填充什么,由父组件而定。
让父组件向子组件指定位置插入html结构,也是一种组件间通信的方式,适用于父组件 => 子组件
话不多说,下面,我们就来看看 slot 的具体如何使用吧!
二、插槽的三种使用方法
1.默认插槽
有两个组件,App是父组件,Child是子组件
父组件代码如下:
<template>
<div class="parent">
<span>我是父组件</span>
<Child></Child>
</div>
</template>
<script>
import Child from './components/Child'
export default {
name:'app',
components:{
Child
}
}
</script>
<style scoped>
.parent{
width: 400px;
height: 400px;
background-color: #bfa;
}
</style>
子组件的代码:
<template>
<div class="child">
<div>我是子组件</div>
<br>
<slot>我是默认插槽,当父组件不填充任何内容时,我这句话才会出现</slot>
</div>
</template>
<script>
export default {
name:'Child',
data() {
return {
}
},
};
</script>
<style>
.child {
width: 200px;
height: 200px;
background-color: lightblue;
margin: auto;
}
</style>