vue3 如何判断组件中的 slot 是否有填充?

发布时间 2023-12-29 16:28:02作者: 蓓蕾心晴

两种方法:

1、通过 this.$slots.name

<div class="btn-icon" v-if="$slots.icon">
      <slot name="icon"></slot>
 </div>

2、通过 useSlots 判断

<template>
    <div>
        <slot/>
        <slot name="test"/>
        <span v-if=slotTest>123</span>
    </div>
</template>

<script lang="ts" setup>
import { useSlots } from "vue";
//判断<slot/>是否有传值
const slotDefault = !!useSlots().default;
//判断<slot name="test"/>是否有传值
const slotTest = !!useSlots().test;
</script>

参考