组件通信方式之插槽
直接上代码ba~
父组件
<template>
<div class="box">
<h2>父组件</h2>
<div class="child">
<Child1>
<pre>默认插槽1</pre>
<pre>默认插槽2</pre>
<!-- v-slot只能添加在<template>上 -->
<!-- 具名插槽填充a v-slot指令可以简化为# -->
<!-- <template v-slot:a> 可以简写为 <template #a>-->
<template #a>
<p>具名插槽a</p>
</template>
<template #b>
<p>具名插槽b</p>
<hr />
</template>
</Child1>
<Child2 :todos="todos">
<template v-slot="{ $row, $index }">
<p :style="{ color: $row.done ? 'green' : 'black' }">
{{ $row.title }}---{{ $index }}--{{ $row.done }}
</p>
</template>
</Child2>
</div>
</div>
</template>
<script setup lang="ts">
import Child1 from "./Child1.vue";
import Child2 from "./Child2.vue";
import { ref } from "vue";
//todos数据
let todos = ref([
{ id: 1, title: "吃饭", done: true },
{ id: 2, title: "睡觉", done: false },
{ id: 3, title: "打豆豆", done: true },
{ id: 4, title: "打游戏", done: false },
]);
</script>
<style scoped>
.box {
width: 600px;
height: 400px;
background: skyblue;
}
.child {
display: flex;
}
</style>
子组件1(使用默认插槽、具名插槽)
<template>
<div class="child1">
<h3>默认插槽</h3>
<slot></slot>
<h3>具名插槽</h3>
<slot name="a"></slot>
<slot name="b"></slot>
</div>
</template>
<script setup lang="ts"></script>
<style scoped>
.child1 {
width: 300px;
height: 300px;
background: yellowgreen;
}
</style>
子组件2(使用作用域插槽)
<template>
<div class="child2">
<ul>
<li v-for="(item, index) in todos" :key="item.id">
<!--作用域插槽:可以讲数据回传给父组件-->
<slot :$row="item" :$index="index"></slot>
</li>
</ul>
</div>
</template>
<script setup lang="ts">
//通过props接受父组件传递数据
defineProps(["todos"]);
</script>
<style scoped>
.child2 {
width: 300px;
height: 300px;
background: hotpink;
}
</style>
总结
1.插槽:
默认插槽
、具名插槽
、作用域插槽
作用域插槽:就是可以传递数据的插槽,子组件可以将数据回传给父组件,父组件可以决定这些回传的数据是以何种结构或者外观在子组件内部去展示!!!
如有错误,欢迎指出,我修正!谢谢!