Optional parent element in Vue.js

2020-02-11 04:01发布

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?

标签: vue.js vuejs2
3条回答
ら.Afraid
2楼-- · 2020-02-11 04:20

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 -->
查看更多
Explosion°爆炸
3楼-- · 2020-02-11 04:29

You could use a combination of custom components and named slots to alleviate duplication of children, for example:

<custom-component>
    <a :href="link" slot="slot-name-here" v-if="link">
        <custom-content-component></custom-content-component>
    </a>
    <div slot="slot-name-here" v-else>
        <custom-content-component></custom-content-component>
    </div>
</custom-component>

Or if the content you want to change is not too complex maybe you could look into using v-html

查看更多
The star\"
4楼-- · 2020-02-11 04:33

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.

查看更多
登录 后发表回答