1

What I'm trying to say is the v-if directive can make an entire component (and all its content) disappear based on a condition.

My question is: is there a way to make only the surrounding tag or component disappear, without removing its content?

Freder
  • 51
  • 1
  • 5

3 Answers3

1

You can use dynamic component and :is prop with vue-fragment when you need a root-less component, or directly vue-fragment if that's just what you need.

Another option is to manipulate the DOM directly.

tony19
  • 125,647
  • 18
  • 229
  • 307
Dicren
  • 505
  • 5
  • 12
0

No, you can't do it. The first thing came to my mind is to move your content in separate component to avoid code duplicating and do something like this

<wrapper v-if="condition">
  <child />
</wrapper>
<child v-else />

If you provide some details on why do you need this, probably we can find a better solution.

etischenko
  • 107
  • 4
  • Yeah, that's what I was also thinking about. The problem is that by doing this I'd have to create "an intermediate component". This means that my intermediate component has to reflect all the props of my child component (and I have quite a few props). Is there a fast way to reflect props? (sorry for going a little off-topic) – Freder Apr 14 '21 at 09:40
  • @Freder [Use `component` element](https://stackoverflow.com/a/63775441/9787887)? – Loi Nguyen Huynh Apr 14 '21 at 09:44
0

2022 Working solution:

Create a universal "template wrapper" component:

<!-- VTemplate.vue -->
<template>
  <slot></slot>
</template>

Use it in pair with the <component> component:

<script setup>
import VTemplate from './VTemplate.vue'
</script>

<component :is="condition ? 'li' : VTemplate">Your content</component>
<!-- Where 'li' is your wrapper tag/component that you want to conditionally hide but not its content -->

Bonus:

<component :is="condition ? 'li' : VTemplate" :class={'list-item': condition}>
    Your content
</component>
<!-- You can assign attributes like the class to it as well -->

P.s. Also, if anyone knows how to import the <template> component directly or at least how to use it in <component :is> please enlighten :)

Seangle
  • 359
  • 2
  • 10