13

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.

Virtual Device
  • 1,650
  • 3
  • 10
  • 26

2 Answers2

24

<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

clod9353
  • 1,942
  • 2
  • 5
  • 20
  • 1
    I got it. Thanks! Do you have the link to the documentation? – Virtual Device Jan 17 '21 at 23:55
  • 2
    You can find some information [here](https://v3.vuejs.org/guide/component-basics.html#dynamic-components) – clod9353 Jan 18 '21 at 00:00
  • Is it possible instead of `
    ` or `` put a custom component with props required? If so, how should one pass the props?
    – Virtual Device Jan 18 '21 at 02:41
  • 1
    yes it is possible. This should answer your question: [https://stackoverflow.com/questions/43658481/passing-props-dynamically-to-dynamic-component-in-vuejs](https://stackoverflow.com/questions/43658481/passing-props-dynamically-to-dynamic-component-in-vuejs) – clod9353 Jan 18 '21 at 07:49
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.

J. Titus
  • 9,535
  • 1
  • 32
  • 45