Optional parent element in Vue.js

前端 未结 3 1276
走了就别回头了
走了就别回头了 2020-12-17 21:26

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:



        
相关标签:
3条回答
  • 2020-12-17 22:16

    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

    0 讨论(0)
  • 2020-12-17 22:16

    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.

    0 讨论(0)
  • 2020-12-17 22:17

    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 -->
    
    0 讨论(0)
提交回复
热议问题