Exploring Inertia 3 Beta: Modernizing the Laravel-Vue Bridge
Overview
Prerequisites
To follow this guide, you should be familiar with:
Key Libraries & Tools
- Inertia Vite Plugin: A new package that handles both client-side and SSR builds without requiring separate server configurations.
- useHTTP Hook: The new internal client for handling fetch requests, replacing the need for external HTTP libraries.
- Optimistic Router: A specialized routing method that updates the UI before the server confirms success.
Code Walkthrough
Simplified Initialization
In version 2, initializing
// resources/js/app.ts
import { createInertiaApp } from '@inertiajs/vue3'
import { resolvePageComponent } from 'laravel-vite-plugin/inertia-helpers'
createInertiaApp({
resolve: (name) => resolvePageComponent(`./Pages/${name}.vue`, import.meta.glob('./Pages/**/*.vue')),
setup({ el, App, props, plugin }) {
createApp({ render: () => h(App, props) })
.use(plugin)
.mount(el)
},
})
Implementing Optimistic Updates
Instead of showing a loading spinner while the server processes a request, router.optimistic allows the UI to reflect changes instantly. If the request fails,
// Inside a Vue component
const handleToggleFavorite = () => {
router.optimistic({
isFavorite: !props.isFavorite
}).post(`/bookmarks/${props.id}/favorite`);
};
Native HTTP without Axios
useHttp hook.
import { useHttp } from '@inertiajs/vue3';
const { get } = useHttp();
const handleSearch = (query) => {
get('/search', { q: query }, {
onSuccess: (results) => { /* handle results */ }
});
};
Syntax Notes
- Method Chaining: The
router.optimistic()method is prepended to standard request methods like.post()or.put(). - SSR Automation: You can delete your
ssr.tsfile entirely;Vitenow handles this through the plugin configuration.
Practical Examples
- Toggling Likes: Use optimistic updates for "Like" buttons to provide instant feedback.
- Global Layout Control: Utilize
useLayoutPropsto dynamically hide sidebars or change page titles from deep within child components without complex event emitting.
Tips & Gotchas
- Beta Warning: Since this is a beta release, avoid using it in high-stakes production environments until the stable release expected around April.
- Error Handling: Exception rendering is now handled via
Inertia::handleExceptionsUsing()in yourAppServiceProvider, allowing you to return customVue.jserror pages instead of the standardLaravelignition page.
