Certainly! The issue here is that the WhenVisible component from Inertia.js only provides the lazy-loaded prop (details) within its slot scope. Outside of the WhenVisible block, details is still undefined unless you trigger another request, which leads to multiple backend calls and inefficiency.
How to solve this:
You want to load details only once (when it becomes visible), and then use it anywhere in your component without triggering additional requests. The best approach is to capture the loaded details in a local reactive variable when it first loads, and then use that variable throughout your component.
Here's how you can do it in Vue (assuming Vue 3 with <script setup> syntax):
<script setup>
import { ref } from 'vue';
const details = ref(null);
</script>
<template>
<div class="container flex flex-col gap-y-6 lg:gap-y-8">
<WhenVisible data="details" v-slot="{ details: loadedDetails }">
<template #fallback>
Loading...
</template>
<div class="hidden lg:flex flex-col mt-6">
<h1 class="text-lg font-medium text-dark-900">
{{ loadedDetails.title }}
</h1>
</div>
<div class="hidden lg:block">
<component :is="comp1" :values="loadedDetails"/>
</div>
<!-- Save the loaded details for later use -->
<template v-if="!details">
<span v-if="details = loadedDetails"></span>
</template>
</WhenVisible>
<!-- Some other elements are here -->
<!-- Use the cached details everywhere else -->
<div v-if="details">
{{ details.description }}
</div>
</div>
</template>
Explanation:
- We declare a
refcalleddetailsto store the loaded data. - Inside the
WhenVisibleslot, whendetailsis loaded, we assign it to our localdetailsref (using a little trick with<span v-if="details = loadedDetails"></span>to set it reactively). - Now, anywhere else in your template, you can use
detailswithout triggering another backend request. - This avoids the need for custom API calls or multiple
WhenVisiblecomponents.
Note:
If you are using Vue 2 with the Options API, you can use data() and this.details instead, but the concept is the same: cache the loaded data in a variable accessible to the whole component.
Summary:
Cache the lazy-loaded prop in a local variable when it first loads, then use that variable everywhere else in your component. This avoids multiple backend requests and keeps your code efficient and clean.