组件通信方式之插槽

组件通信方式之插槽
直接上代码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.插槽:默认插槽具名插槽作用域插槽
作用域插槽:就是可以传递数据的插槽,子组件可以将数据回传给父组件,父组件可以决定这些回传的数据是以何种结构或者外观在子组件内部去展示!!!

更多插槽相关知识请查看官网介绍

如有错误,欢迎指出,我修正!谢谢!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值