Stephan-v
Stephan-v

Reputation: 20309

Toggle a v-if on a slot component?

I am trying to use the intersectionObserver to prevent loading of components up until the point that they are scrolled into view like so:

Usage example:

<lazy-component>
    <newsletter slot-scope="{}"></newsletter>
</lazy-component

The lazy component is a single file component which holds this template:

LazyComponent.vue

<template>
    <span>
        <slot v-if="visible"></slot>
    </span>
</template>

The newsletter component would get rendered if I did not add a slot-scope on it because it gets rendered first and only then gets inserted into the slot with a v-if statement.

At this point the component has been loaded and the if this would be an async component its Javascript would have been loaded as well. This is what I am trying to prevent.

Although the slot-scope works this feels pretty hacky and not clear to other users.

Would it be possible to set a v-if to false on the component in my templates and have the lazy-component manually set the v-if to true somehow?

Upvotes: 0

Views: 982

Answers (1)

Vamsi Krishna
Vamsi Krishna

Reputation: 31352

If I understand you right you can do it by passing visible as a data to the slot.

LazyComponent.vue

<template>
    <span>
        <slot :visible="visible"></slot>
    </span>
</template>

Using LazyComponent

<lazy-component>
    <newsletter slot-scope="{visible}" v-if="visible"></newsletter>
</lazy-component

Upvotes: 1

Related Questions