When using Inertia.js, you can pass data to your layout component using either standard Vue props or Inertia's shared data ($page.props). Both approaches are valid, but using $page.props can be more convenient in some cases.
To pass data to your layout component using standard Vue props, you can simply define the props in your layout component and pass them down from your page components. For example:
// Layout.vue
<template>
<div>
<h1>Welcome, {{ user.name }}!</h1>
<slot></slot>
</div>
</template>
<script>
export default {
props: {
user: {
type: Object,
required: true,
},
},
};
</script>
// Page.vue
<template>
<layout :user="user">
<h2>Page content goes here</h2>
</layout>
</template>
<script>
import Layout from '@/layouts/Layout.vue';
export default {
components: {
Layout,
},
data() {
return {
user: {
name: 'John Doe',
},
};
},
};
</script>
To use Inertia's shared data ($page.props) in your layout component, you can import it using the usePage function provided by Inertia. For example:
// Layout.vue
<template>
<div>
<h1>Welcome, {{ user.name }}!</h1>
<slot></slot>
</div>
</template>
<script>
import { usePage } from '@inertiajs/inertia-vue3';
export default {
setup() {
const { props } = usePage();
return {
user: props.user,
};
},
};
</script>
Note that when using Inertia's shared data, you don't need to pass any props from your page components to your layout component. Instead, you can simply access the data directly from $page.props in your layout component.
As for importing Inertia's shared data, you only need to do it once in your top-level component (usually App.vue). This will make the data available to all child components, including your layout component. For example:
// App.vue
<template>
<div>
<layout>
<router-view />
</layout>
</div>
</template>
<script>
import Layout from '@/layouts/Layout.vue';
import { InertiaApp } from '@inertiajs/inertia-vue3';
export default {
components: {
Layout,
InertiaApp,
},
mounted() {
// Initialize Inertia.js
this.$inertia.init();
},
};
</script>