Is there any way to define the parent element as optional based on a condition but always show its children in Vue.js?
For example:
<a :href="link">Some text</a>
What I would like to achieve is the following DOM depending on link
<a href="somelink">Some text</a> <!-- when link is truthy -->
Some text <!-- when link is falsy -->
Potential solutions
Duplicate the children:
<a :href="link" v-if="link">Some text</a> <template v-if="!link">Some text</template>
But that is not a good solution especially as there might be more content than just a simple text.
Write my own component that does the logic depending on some attribute. But this seems overkill and also has to be flexible enough for different kind of element types or attributes.
As I don't like either of these approaches, I wonder whether there is no simpler solution. Any ideas?
After some more digging, I found a way that works and is actually very simple. It uses the
is
special attribute that is actually meant to be used when you cannot bind components to HTML elements directly.This will result in either of the following:
You could use a combination of custom components and named slots to alleviate duplication of children, for example:
Or if the content you want to change is not too complex maybe you could look into using
v-html
Not sure why my previous answer was deleted.Turns out you can't just C&P answers across multiple Qs. I've gone ahead and flagged the other Qs as dups of this one (I'm trying here... come on moderators...)I've run into this exact issue several times myself and decided to go ahead and create a module with the solution I've been using locally, which can find on NPM:
vue-wrapped-component
This module provides a functional Vue component that allows any component or element to be conditionally wrapped using another component or element.
The previous answers semi-work for very basic of circumstances. This module provides a more robust solution that works in almost any situation, especially complex ones where there's a risk of duplicating lots of code just because you need a simple conditional wrapper.