Vue3如何检查子组件类型

需求:

检查parent组件的子组件是否为children组件

<parent>
	<children></children>
</parent>

解决方法

拿到context.slots.default(),其中包含了parent组件下所有子组件的信息

然后遍历context.slots.default(),其中有type属性,通过type属性我们可以知道每一个子组件的类型,是div还是span还是children…

import children from 'xxx'

export default {
  name: 'parent',
  setup(props, context) {
    // 注意!这里是default()函数,而不是熟悉,需要加括号执行!!
    const defaults = context.slots.default()
    
    // 遍历defaults
    defaults.forEach((tag)=>{
      // 判断类型
      // 注意!!如果这里的children是你自定义属性的名字,记得在上面import
      if(tag.type !== children) {
        throw new Error('The child component of parent must be children')
      }
    })

    return {
      defaults
    }
  }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Vue 3 中,你可以使用 `ref` 和 `props` 来实现组件获取组件。 首先,在组件中,你需要将希望组件获取的数据通过 `props` 进行传递。例如,假设你想获取组件的一个名为 `childData` 的属性,可以将其定义为组件的 `props`: ```vue <template> <div> <!-- 组件内容 --> </div> </template> <script> export default { props: { childData: { type: String, // 根据实际情况,修改数据类型 required: true // 根据实际情况,修改是否必需 } }, // ... } </script> ``` 然后,在组件中,你可以通过使用 `ref` 来引用组件,并使用 `.value` 来访问组件传递的数据。例如: ```vue <template> <div> <!-- 组件内容 --> <child-component ref="child"></child-component> <button @click="getChildData">获取组件数据</button> </div> </template> <script> import { ref } from "vue"; export default { components: { ChildComponent }, setup() { const childComponentRef = ref(null); // 创建一个 ref const getChildData = () => { const childData = childComponentRef.value.childData; console.log(childData); // 在控制台输出组件的数据 }; return { childComponentRef, getChildData } } } </script> ``` 在上述代码中,我们通过 `ref` 创建了一个 `childComponentRef`,然后将其赋值给组件的 `ref` 属性。在 `getChildData` 方法中,我们通过 `childComponentRef.value.childData` 来访问组件的数据。 这样,组件就可以获取组件传递过来的数据了。当然,你还可以根据实际需求进行修改和适配。希望能帮到你!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值