slot 意为“插槽”,其作用为子组件预约一个html空间,由调用他的父组件来实现这个空间的具体显示内容。父组件中决定要插入到子组件中的内容,而子组件自行决定插槽的位置。
1.匿名slot
2.具名slot
3.作用域slot
1.匿名slot
首先在子组件中需要父组件来确定显示内容的位置定义一个slot。
<template>
<div>
<slot></slot>
<h1>我是子組件</h1>
</div>
</template>
然后在父组件中的子组件标签下加入带有slot属性的标签,并在其中编写想要实现的代码片段
<template>
<div>
<h1>我是父組件</h1>
<son-component>
<div slot>
<h2>父組件要顯示的內容</h2>
</div>
</son-component>
</div>
</template>
显示结果:
2.具名slot
给slot标签添加name属性即所谓的具名slot,可以用v-slot属性来确定匹配的slot
子组件
<template>
<div>
<h1>我是子組件的頂部</h1>
<slot name="slotOne"></slot>
<slot name="slotTow"></slot>
<h1>我是子組件的底部</h1>
</div>
</template>
父组件
<template>
<div>
<h1>我是父組件</h1>
<son-component>
<template v-slot:slotOne>
<h2>父組件要顯示的slotOne內容</h2>
</template>
<template v-slot:slotTow>
<h2>父組件要顯示的slotTow內容</h2>
</template>
</son-component>
</div>
</template>
显示结果:
3.作用域插槽
作用域插槽,就是实现在子组件中自行决定自己要显示什么内容。
子组件
<template>
<div>
<h1>我是子組件的頂部</h1>
<slot name="slotOne" :data='msg1'></slot>
<slot name="slotTow" :data='msg2'></slot>
<h1>我是子組件的底部</h1>
</div>
</template>
<script>
export default {
name: "sonComponent",
data() {
return {
msg1:"我是子組件發來的第一條消息",
msg2:"我是子組件發來的第二條消息",
};
},
components: {
},
computed: {
},
mounted: {
},
methods: {
},
};
</script>
<style lang='less' scoped>
</style>
父组件
<template>
<div>
<h1>我是父組件</h1>
<son-component>
<template v-slot:slotOne="{data}">
<h2>父組件要顯示的slotOne內容msg:{
{
data}}</h2>
</template>
<template v-slot:slotTow="{data}">
<h2>父組件要顯示的slotTow內容msg:{
{
data}}</h2>
</template>
</son-component>
</div>
</template>
<script>
import sonComponent from "./slotTestSon";
export default {
name: "fatherComponent",
data() {
return {
};
},
components: {
sonComponent,
},
computed: {
},
mounted: {
},
methods: {
},
};
</script>
<style lang='less' scoped>
</style>