vue.jsdom

In vue, can you avoid DOM repetition for conditional situations where only the parent changes?


The wrapper is only thing that changes. In this example, it's just a simple swapping change.

It doesn't matter whether it's a boolean or switch-case situation. I assume this need arises often.

<template>
  <div class="my-component>
    <div v-if="myBool">
      <MyCoolComponent
        :it="prop1"
        :has="prop2"
        :lots="prop3"
        :of="prop4"
        :properties="prop5" />
    </div>
    <AnotherComponent v-else>
      <MyCoolComponent
        :it="prop1"
        :has="prop2"
        :lots="prop3"
        :of="prop4"
        :properties="prop5" />
    </AnotherComponent>
  </div>
</template>

In my use case, the boolean controls whether to use <TransitionGroup>.

Context: VueJS, vue3, composition API.


Solution

  • Since MyCoolComponent has the same level of nesting in both cases, dynamic component can be used:

    <component :is="myBool ? 'div' : AnotherComponent">
      <MyCoolComponent ... />
    </div>