Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
561 views
in Technique[技术] by (71.8m points)

vuejs2 - Optional parent element in Vue.js

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...