如何在运行时确保传的子组件的类型

76 阅读1分钟

v2-809a23dd4cd0de81fcf03baf240827a3_r.jpg

用 useSlots 判断

比如 我只想要 Tabs组件 里面只能用 Tab组件, 用法如下:

<Tabs>
    <Tab>我是子组件</Tab>
</Tabs>

实现

<template>
    <div>
	<component v-for="c in defaults" :is="c">
	<slot />
    </div>
</template>
// 为什么不直接用slot呢,因为slot会直接把所有内容渲染出来,虽然 js 还是会报错,但这样不好
// 用 component 会调用 defaults 把子组件一个一个渲染出来,这样比较符合
<script setup>
import { ref, useSlots } from 'vue';
import Tab from '@/lib/Tab.vue';

const slots = useSlots()
// 默认插槽 都在 default里,它是一个函数,执行后就能看到里面有多少个标签
console.log('slots', slots.default())
用返回的某一个元素里面的Type属性去和 Tab组件对比,如果是 那就是 TRUE
console.log('slots', slots.default()[0].type === Tab)

const defaults = slots.default()
defaults.forEach(item => {
	if (item.type !== Tab) {
		throw new Error('组件Tabs 里面的子标签只能是组件 Tab')
	}
})
</script>