vue3插槽slot的使用

一,默认插槽

父组件页面:使用子组件标签

<template>
  <div>我是父组件自己的内容</div>
  <ComTest></ComTest>  // 这里使用子组件的内容
  <!-- <ComTest>我要替换默认插槽的内容</ComTest>  // 这里替换子组件的内容  -->
</template>
<script setup lang='ts'>
  import ComTest from '../components/ComTest.vue';
</script>

子组件:使用<slot></slot>

<template>
  <div >
    <slot>我是默认插槽</slot>
  </div>
</template>

二,具名插槽

父组件页面:使用 <template v-slot:插槽名></template >

<template>
  <div>我是父组件自己的内容</div>
  <ComTest >
  <!--插槽语法糖 v-slot:header 等于 #header  -->
    <template v-slot:header>   
        替换具名插槽头部默认信息
    </template>
     <!--插槽语法糖 v-slot:main 等于 #main  -->
    <template v-slot:main>
        替换具名插槽中间默认信息
    </template>
       <!--插槽语法糖 v-slot:footer 等于 #footer-->
    <template v-slot:footer>
        替换具名插槽底部默认信息
    </template>
    </ComTest>
</template>

子组件:使用<slot name="插槽名"></slot>

<template>
  <div >
    <header>
      <slot name="header">我是具名插槽头部默认信息</slot>
    </header>
    <main>
      <slot name="main">我是具名插槽中间默认信息</slot>
    </main>
    <footer>
      <slot name="footer">我是具名插槽底部默认信息</slot>
    </footer>
  </div>
</template>

三,作用域插槽

父组件页面:使用 <template v-slot:插槽名 = "scope">{{scope.属性名}}</template >

<template>
  <div>我是父组件自己的内容</div>
  <ComTest >
    <template v-slot:header="scope">
       {{ scope.msg}}  
       <!-- 我是作用域插槽头部信息 -->
    </template>
    <template v-slot:main="scope">
        {{ scope.msg  }}
        <!-- 我是作用域插槽中间信息 -->
    </template>
    <template v-slot:footer="scope">
        {{ scope.msg  }}
        <!-- 我是作用域插槽底部信息 -->
    </template>
  </ComTest>
</template>

子组件:使用<slot name="插槽名" 属性名='属性值'></slot>

<template>
  <div >
    <header>
      <slot name="header" msg="我是作用域插槽头部信息">我是具名插槽头部默认信息</slot>
    </header>
    <main>
      <slot name="main" msg="我是作用域插槽中间信息">我是具名插槽中间默认信息</slot>
    </main>
    <footer>
      <slot name="footer" msg="我是作用域插槽底部信息">我是具名插槽底部默认信息</slot>
    </footer>
  </div>
</template>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

coderkey

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值