v-if on a DIV but always display its contents with

2019-06-28 06:35发布

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

<div v-if="showparent" class="parent">
  <div class="child"> 
    Child should always be visible
  </div>
</div>

As far as I know this is not possible with Vue.js. The v-if directive removes all div's inside when showparent is false.

Any ideas how to achieve this?

标签: vue.js
2条回答
我只想做你的唯一
2楼-- · 2019-06-28 07:23

Hiding a div hides all contained (child) divs. Move the parent out into a container div, do not nest the child div in it.

查看更多
来,给爷笑一个
3楼-- · 2019-06-28 07:35

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..) :

<div v-if="showparent" class="parent">
  <div class="child"> 
    Child should always be visible
  </div>
</div>
<div v-else class="child">
    Child should always be visible
</div>

Or you can create a custom component:

export default {
    name: "v-if-parent",
    props: {
        condition: {
            type: Boolean,
            required: true
        }
    },
    render(el) {
        if (this.condition) {
            let parent = this.$scopedSlots.parent()[0];
            parent.children = this.$scopedSlots.default();
            return parent;
        } else {
            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('div', null, children)
            }
            return children;
        }
    }
}

And then use it like this

<v-if-parent :condition="showparent">
  <template #parent><a href="somelink" /></template>
  This text is always visible <span>You can include absolutely whatever you want in the default slot</span>
</v-if-parent>
查看更多
登录 后发表回答