Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to conditionally render layouts?

I want to change layouts in a component depending on a condition from this:

<template>
  <layoutA>
    //component contents
  </layoutA>
</template>

to this:

<template>
  <layoutB>
    //component contents
  </layoutB>
</template>

The only way I know of how to render components with a condition is with v-if which doesn’t render child components, if the condition is not met. I could do this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<template>
  <layoutA v-if="condition">
    //component contents
  </layoutA>
  <layoutB v-else>
    //component contents
  </layoutB>
</template>

but with large components this gets messy quickly + I would have to maintain the same code twice. It could be simplified by moving //component contents into its own component and import it twice. Is there a more elegant way to do this?

Here’s an example of a layout:

<template>
  <v-nav/>
  <slot/>
  <v-footer/>
</template>

>Solution :

This is the case for dynamic component:

  <componenent :is="condition ? 'layoutA' : 'layoutB'">
    //component contents
  </componenent>

For more complex expression it can be moved to computed property.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading