个人技术分享

一,默认插槽

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

<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>