is special attribute vs v-if / v-show

Viewed 277

is special attribute is:

<!-- Component changes when currentTabComponent changes -->
<component v-bind:is="currentTabComponent"></component>

conditional rendering is:

<div v-if="type === 'A'">
  A
</div>
<div v-else-if="type === 'B'">
  B
</div>
<div v-else-if="type === 'C'">
  C
</div>
<div v-else>
  Not A/B/C
</div>

I know the different between using v-if and v-show, but I don't know the difference between using a list of v-ifs for different cases vs using the is special attribute. When should I use them?

Does is work like v-if or v-show? I mean, does it render all the components anyways? Is is like a syntactic sugar for a list of subsequent v-ifs?

1 Answers

is would be useful if the list of v-ifs would all render a component if true.

Like so:

<template v-if="component == "firstComponent">
    <first-component></first-component>
<template v-else-if="component == "secondComponent">
    <second-component></second-component>
</template>
<template v-else-if="component == "thirdComponent">
    <third-component></third-component>
</template>

This can then be reduced to:

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

Concerning your second question

Wether component :is works like v-if or v-show depends on wether you wrap it in <keep-alive> or not. Read the documentation on this here. Note though, that using <component> a component only gets created until it is necessary the first time, wether you use <keep-alive> or not.

So:

  • v-if (re)creates the component everytime the condition is met.
  • <component :is="..."> creates the component everytime the condition is met (like v-if).
  • <keep-alive><component :is="..."></keep-alive> creates the component at most 1 time (but possibly 0).
  • A component with only v-show on it is created exactly once.
Related