skip to Main Content

I have created a component in Vue JS named "Component". I have learnt that we use the comoponent in a parent component template like this.

<template>
   <p>I am a heading </p>
   <Component/>
</template>

But if I use the Component syntax like an HTML DOM element syntax and embed more HTML markup inside it, what does it mean actually? I am new to Vue JS and have no idea about this.

<template>
   <Component>
      <div> 
       Hello I am a div 
      </div>
  </Component>
</template>

2

Answers


  1. As you mentioned there are two ways of using Custom components.

    We usually use the self-closing tag component if we are not passing any child elements

    If you need to pass a child to the component you have to use the second method. A child inside a component is called a slot

    You can read more about slots aka child components in this article

    Login or Signup to reply.
  2. The HTML markup inside Component tags goes to a slot defined in the component.
    So, if Component is defined something like below

    <template>
    <h1>This is content of component</h1>
    <slot></slot>
    </template>
    

    and used in parent component as below

    <template>
      <Component>
        <div> 
          Hello I am a div 
        </div>
      </Component>
    </template>
    

    then following will actually be rendered

    <h1>This is content of component</h1>
    <div> 
      Hello I am a div 
    </div>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search