15

I just started to learn Vuejs, and in on one of the singe file components I need to work with there is a a structure that I don't clearly understand:

<template>
   <component :is="user === undefined ? 'div' : 'card'"> 
  
   ...some code

   </component>
</template>

In what cases it is useful? Why can't we use <div> instead?

I'm asking that question here because every time I google Vue component tag I am getting info about components themselves and nothing tag related.

2 Answers 2

27

<component> is a special vue element that is used in combination with the is attribute. What it does is to conditionally (and dynamically) render other elements, depending on what is placed inside the is attribute.

<component :is="'card'"></component>

Will render the card component in the DOM. The example shown in your code:

<component :is="user === undefined ? 'div' : 'card'"> 

will render a div when user is undefined, and a card component otherwise.

This behavior is dynamic, so if user changes from undefined to someghing else, vue will remove the div from the DOM, and will insert the card component.

In the HTML, you will never see a node called <component>, just a div or a card

Sign up to request clarification or add additional context in comments.

4 Comments

I got it. Thanks! Do you have the link to the documentation?
You can find some information here
Is it possible instead of <div> or <card> put a custom component with props required? If so, how should one pass the props?
2

<component> is used when you need to dynamically render a specific tag (specified by :is) based on a certain piece of information (usually a prop). In the example you posted, you have two scenarios:

  1. user is undefined, thus rendering <component> as a <div>
  2. user is not undefined, thus rendering <component> as a <card>

<card> is most likely a custom component with its own specific template and logic.

2 Comments

Ohhh so <component> essentially transform into whatever html element is passed in as a :to prop?
:is attribute, not :to prop, but yes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.