vue3+vite+ts--插槽slot的详细使用

目录

一、插槽的作用

二、匿名插槽(默认插槽)

三、具名插槽

四、动态插槽名

五、作用域插槽


一、插槽的作用

- 插槽是Vue中常见的一种组件间的相互通信方式,作用是让父组件可以向子组件指定位置插入html结构,适用于父子组件,在要接收数据的组件页面通过<slot>标签来表示,简单来说,就是通过此标签来起到占位的作用,而要插入的内容也会对应到标签所在的位置,插槽又分为匿名插槽、具名插槽、作用域插槽

二、匿名插槽(默认插槽)

<template>
  <div class="">
    <slot></slot>
  </div>
</template>
<script lang="ts" setup></script>
<style lang="scss" scoped></style>

三、具名插槽

- 顾名思义插槽有名字,子组件在<slot>标签上name="插槽名字"父组件只需要写v-slot:插槽名字或者#插槽名字

- 父组件

<template>
  <h1>我是父组件</h1>
  <slotcmom>
    <template v-slot:head><div>我是头部</div></template>
    <template #mian><div>我是身体</div></template>
    <template v-slot:footer><div>我是脚部</div></template>
  </slotcmom>
</template>
<script setup lang="ts">
import slotcmom from './components/slotcmom.vue';
</script>
<style scoped></style>

- 子组件

<template>
  <div class="">
    <h2>我是子组件</h2>
    <div>子组件头部</div>
    <slot name="head"></slot>
    <div>子组件内容</div>
    <slot name="mian"></slot>
    <div>子组件脚部</div>
    <slot name="footer"></slot>
  </div>
</template>
<script lang="ts" setup></script>
<style lang="scss" scoped></style>

- 结果

 四、动态插槽名

- 在父组件把插槽名字设置为变量

- 父组件

<template>
  <h1>我是父组件</h1>
  <slotcmom>
    <template #[isSlotName]><div>我是父组件内容</div></template>
  </slotcmom>
</template>
<script setup lang="ts">
import slotcmom from './components/slotcmom.vue';
import { ref } from 'vue';
const isSlotName = ref<string>('mian');
</script>
<style scoped></style>

- 子组件

<template>
  <div class="">
    <h2>我是子组件</h2>
    <div>子组件头部</div>
    <slot name="head"></slot>
    <div>子组件内容</div>
    <slot name="mian"></slot>
    <div>子组件脚部</div>
    <slot name="footer"></slot>
  </div>
</template>
<script lang="ts" setup></script>
<style lang="scss" scoped></style>

 - 结果

五、作用域插槽

- 子组件向父组件传递数据的一种形式,子组件在<slot>具名标签或者匿名标签上绑定数据,父组件在<template>标签上获取数据

- 父组件

<template>
  <h1>我是父组件</h1>
  <slotcmom>
    //可以通过解构#data="{getDatas}"
    <template #data="scope">
      <div>{{ scope }}</div>
    </template>
  </slotcmom>
</template>
<script setup lang="ts">
import slotcmom from './components/slotcmom.vue';
</script>
<style scoped></style>

- 子组件

<template>
  <div class="">
    <h2>我是子组件</h2>
    <slot name="data" :getData="getData"></slot>
  </div>
</template>
<script lang="ts" setup>
import { reactive } from 'vue';
type propGetData = {
  slotData: string;
};
const getData = reactive<propGetData>({
  slotData: '子组件的数据'
});
</script>
<style lang="scss" scoped></style>

- 结果

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值