slot的理解:是‘占位符’,在组件模板中占好了位置,当使用该组件标签的时候,组件标签里面的内容就会自动填充(替换组件模板中的位置)
首先准备两个组件:Father.vue和children.vue组件
在Father.vue组件中引入children.vue组件
<script>
import Children from '../components/children.vue'
export default {
components:{
Children
}
}
</script>
slot的使用:
1.匿名插槽(默认插槽)
//在Father.vue组件中写
<template>
<div>
这是父组件
<children>
<div style="background:red">
这是插槽练习,这是父组件中引入的children组件标签里的内容,这段话会通过 slot插槽显示,如果children组件中没有slot标签,这段话就不会显示
</div>
</children>
<div>
该标签内容在children标签下面,会正常显示
</div>
</div>
</template>
<script>
import Children from '../components/children.vue'
export default {
components:{
Children
}
}
</script>
//在children.vue组件中写
<template>
<div class="children">
这是子组件中的内容
//匿名插槽
<slot></slot>
</div>
</template>
2.具名插槽
//在Father.vue组件中写
<template>
<div>
这是父组件
<children>
<!-- 具名插槽 -->
<template v-slot:header>
<div>
这是具名插槽header,看看我的位置,children组件中具名插槽header在slot1的下面
</div>
</template>
<template v-slot:slot1>
<div style="border:1px solid green" >
我是具名插槽slot1
</div>
</template>
</children>
<div>
该标签内容在children标签下面,会正常显示
</div>
</div>
</template>
//在children.vue组件中写
<template>
<div class="children">
这是子组件中的内容
<!-- 具名插槽 -->
<slot name="slot1"></slot>
<slot name="header"></slot>
</div>
</template>
3.作用域插槽
//在Father.vue组件中写
<template>
<div>
这是父组件
<children>
<!-- 作用域插槽 -->
<template v-slot:name1="aa" >
<ul>
<li
v-for="item in aa.data" :key="item"
>
{
{
item}}
</li>
</ul>
</template>
</children>
<div>
该标签内容在children标签下面,会正常显示
</div>
</div>
</template>
//在children.vue组件中写
<template>
<div class="children">
这是子组件中的内容
//作用域插槽
<slot name="name1" :data="data"></slot>
</div>
</template>