Optional parent element in Vue.js

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.


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 -->

Tags:

Vue.Js

Vuejs2