v-if on a DIV but always display its contents with Vue.js?

后端 未结 3 1160
[愿得一人]
[愿得一人] 2021-02-20 14:15

With Vue.js I need to toggle a parent-div, but always show the child-div.

3条回答
  •  北恋
    北恋 (楼主)
    2021-02-20 14:44

    I have found two ways to do what you want to achieve, first one is to just repeat the child code in a v-else (not optimal because you need to repeat the code..) :

    Child should always be visible
    Child should always be visible

    Or you can create a custom component:

    
    export default {
        name: "v-if-parent",
        props: {
            condition: {
                type: Boolean,
                required: true
            },
            fallbackWrap: {
                type: String,
                default: 'div'
            }
        },
        render(el) {
            if (this.condition) {
                let parent = this.$scopedSlots.parent()[0];
                if (typeof this.$scopedSlots.default === 'function')
                    parent.children = this.$scopedSlots.default();
                return parent;
            } else if (typeof this.$scopedSlots.default === 'function') {
                let children = this.$scopedSlots.default();
                if (children.length > 1) {
                    //We can only return a single vnode so if multiple children, wrap them in a div
                    return el(this.fallbackWrap, null, children)
                }
                return children[0];
            }
            return null;
        }
    }
    

    And then use it like this

    
      
      This text is always visible You can include absolutely whatever you want in the default slot
    
    

提交回复
热议问题