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.
<a :href="link" :is="link ? 'a' : 'span'">Some text</a>
This will result in either of the following:
<a href="somelink">Some text</a> <!-- when link is truthy -->
<span>Some text</span> <!-- when link is falsy -->
For Vue v3.x, the following would work:
<component
:is="condition ? 'custom-component' : 'v-fragment'"
custom-component-prop
...
>
...
</component>
// VFragment.vue
<template>
<slot></slot>
</template>
<script>
export default {
inheritAttrs: false,
}
</script>
For Vue v2.x, a workaround is to do:
<component
:is="condition ? 'custom-component' : 'v-div'"
custom-component-prop
...
>
...
</component>
// VDiv.vue
<template>
<div>
<slot></slot>
</div>
</template>
<script>
export default {
inheritAttrs: false,
}
</script>
The tradeoff is there will be an extra element like div
being rendered, since Vue v2.x doesn't support fragment.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With