Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 327
Virtual Device Avatar asked Jan 23 '26 07:01

Virtual Device


2 Answers

<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

like image 161
clod9353 Avatar answered Jan 25 '26 19:01

clod9353


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

like image 24
J. Titus Avatar answered Jan 25 '26 21:01

J. Titus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!