Home > OS >  How do I check the component type of values inside the $slots?
How do I check the component type of values inside the $slots?

Time:05-22

I'll provide a simple example that would demonstrate the problem I'm facing.

So I have a page that includes the following code:

<Slider>
  <Slide>
    <p>test 1</p>
  </Slide>
  <Slide> test 2 </Slide>
  <div>test3</div>
</Slider>

The problem is within the mounted section of the Slider.

Inside Slider

<template>
  <div >
    <slot></slot>
  </div>
</template>

<script>
export default {
  data: () => ({
    slides: [],
  }),
  watch: {
    slides() {
      console.log(this.slides);
    },
  },
  mounted() {
    this.$slots.default().forEach((vNode) => {
      console.log(vNode);
      // this.slides.push(node.componentInstance)
    });
  },
};
</script>

How do I check if the vNode is an instance of the Slide component?
The console log return the following object:

{
    "__v_isVNode": true,
    "__v_skip": true,
    "type": {
        "__hmrId": "6e03689e",
        "__file": "<route to project>/src/components/CarouselSlide.vue"
    },
    "props": null,
    "key": null,
    "ref": null,
    "scopeId": null,
    "slotScopeIds": null,
    "children": {
        "_": 1
    },
    "component": null,
    "suspense": null,
    "ssContent": null,
    "ssFallback": null,
    "dirs": null,
    "transition": null,
    "el": null,
    "anchor": null,
    "target": null,
    "targetAnchor": null,
    "staticCount": 0,
    "shapeFlag": 36,
    "patchFlag": 0,
    "dynamicProps": null,
    "dynamicChildren": null,
    "appContext": null
}

Slide is just the following:

<template>
  <div >
    <slot></slot>
  </div>
</template>

<script>
export default {};
</script>

Here is a demo: link

CodePudding user response:

Similarly to React element objects represented by JSX, Vue vnode objects have type property that is a string for DOM elements, and a component for Vue components.

There should be a check:

if (vNode.type === Slide) ...
  • Related