To achieve eager loading of data in a child component using Inertia and SSR, you can utilize Inertia's lazy props feature. This allows you to pass data to components only when they are actually rendered, which is useful for loading data into components that are not known ahead of time.
Here's how you can modify your setup to use lazy props:
-
In your
ContactsBlock.vuecomponent, you will need to use theusePagecomposable to access the lazy prop. -
In your controller, when you return the Inertia response, you can define a closure that will be executed only when the
ContactsBlockcomponent is rendered.
Here's an example of how you can modify your code:
// In your controller method
use Inertia\Inertia;
use Inertia\Response;
public function showPage(): Response
{
return Inertia::render('Page', [
// Define a closure for the 'contacts' prop
'contacts' => fn () => Contact::all(),
]);
}
And in your ContactsBlock.vue component, you can access the contacts prop like this:
<template>
<div>
<p>All contacts</p>
<pre>{{ contacts }}</pre>
</div>
</template>
<script setup>
import { usePage } from '@inertiajs/inertia-vue3';
// Access the lazy prop 'contacts'
const { props } = usePage();
const contacts = props.value.contacts;
</script>
In this setup, the contacts data will only be loaded when the ContactsBlock component is actually rendered, thanks to the lazy evaluation of the closure in the Inertia response.
Please note that the usePage composable is part of the Inertia.js Vue 3 adapter, and the props.value is how you access the props passed to the page component.
Remember that for SSR to work properly with lazy props, you need to ensure that your server-side environment is set up to handle Inertia SSR. This includes having a Node.js server to render the Vue components on the server side.