Virtual Device
Virtual Device

Reputation: 2060

Tag <component> inside Vuejs template

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.

Upvotes: 15

Views: 19696

Answers (2)

clod9353
clod9353

Reputation: 2002

<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

Upvotes: 27

J. Titus
J. Titus

Reputation: 9690

<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.

Upvotes: 2

Related Questions