Home > Software engineering >  Using a component inside another component in VueJS
Using a component inside another component in VueJS

Time:02-17

While I was reviewing headlessui's menu component, I saw the use of 2 components that are nested like the following: (see: https://headlessui.dev/vue/menu)

<template>
  <Menu>
    <MenuButton>More</MenuButton>
    <MenuItems>
      <MenuItem v-slot="{ active }">
       // some content
     </MenuItem>
   </MenuItems>
  </Menue>
</template>

So as you may see, there is a MenuItem component inside of the MenuItems component. And I need something similar to that so I can use a template and put another component's result into that template.

Here the example of what I am trying to do:

<!-- HeadingComponent.vue -->

<div >
    <div >
        {{ title }} <button>Create New</button>
    </div>
    <div >
        <!-- I want to put some component's rendered content here -->
    </div>
</div>

And this is, let's say, a page where I want to use the common component.

<!-- Blog.vue -->

<HeadingComponent :title="Posts">
  <BlogPostsComponent :post="someArray"/> <!-- Some other component which may vary -->
</HeadingComponent>

The question

What kind of changes do I need to do in the component HeadingComponent.vue so it works as I expected?

CodePudding user response:

Just in a short time, I found something like slots in VueJS which is definitely what I was looking for.

Here is the guide page: https://v2.vuejs.org/v2/guide/components-slots

What I did in my problem is that I put <slot></slot> tags inside div whose class is content, and then the last sample I gave (Blog.vue) has worked.

<!-- HeadingComponent.vue -->

<div >
    <div >
        {{ title }} <button>Create New</button>
    </div>
    <div >
        <!-- I want to put some component's rendered content here -->
        <slot></slot>
    </div>
</div>

CodePudding user response:

Slots are a good way to add a component to another or even simple html

docs : https://fr.vuejs.org/v2/guide/components-slots.html

 <h1>Vue JS Slots Application</h1>
    <div id="app">
  <slots>
    <template slot="slotA"><pre>Slot A Content from parent.</pre></template>
    <template><i>Parent Component Content.</i></template> 
  </slots>
  <hr/>
  <slots>
    <template slot="slotB">Replace Slot B Default Content</template>
    <template><b>Replace Default Slot Content.</b></template>
  </slots>
</div>

<template id="aside">
  <div>
  <h3>My Slots App</h3>
  <slot>Default Slot Content</slot><br>
  <slot name="slotA"></slot><br>
  <slot name="slotB"></slot><br>
  </div>
</template>

Example of codepen : https://codepen.io/brian_kim/pen/NpWKGe

  • Related