Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional parent element in Vue.js

Tags:

vue.js

vuejs2

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?

like image 396
str Avatar asked Mar 19 '17 11:03

str


2 Answers

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 -->
like image 161
str Avatar answered Sep 29 '22 22:09

str


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.

like image 44
Wenfang Du Avatar answered Sep 29 '22 20:09

Wenfang Du