wire:navigate
The wire:navigate directive provides SPA-like page navigation by intercepting link clicks and loading pages in the background. Instead of full page refreshes, Livewire fetches new content and swaps it seamlessly, resulting in faster navigation and a smoother user experience.
Basic Usage
This navigation example demonstrates wire:navigate with hover prefetching and redirect functionality:
// wires/BlogPost.bx
class extends="cbwire.models.Component" {
data = {
"title": "",
"content": ""
};
function save() {
// Save blog post
redirect("/blog", true); // Navigate using wire:navigate
}
function cancel() {
redirect("/blog", true);
}
}// wires/BlogPost.cfc
component extends="cbwire.models.Component" {
data = {
"title" = "",
"content" = ""
};
function save() {
// Save blog post
redirect("/blog", true); // Navigate using wire:navigate
}
function cancel() {
redirect("/blog", true);
}
}What wire:navigate Does
When you add wire:navigate to a link, CBWIRE automatically:
Intercepts Clicks: Prevents browser from performing full page visits
Background Fetching: Requests new page content via AJAX with loading indicator
Seamless Swapping: Replaces URL,
<title>, and<body>content without refreshPerformance Boost: Often achieves 2x faster page loads than traditional navigation
Available Modifiers
The wire:navigate directive supports one modifier:
Hover:
.hover- Prefetches page content when user hovers over link for 60ms
Example: wire:navigate.hover improves perceived performance but increases server usage.
Navigation Process
Here's what happens during navigation:
User clicks a
wire:navigatelinkLivewire prevents default browser navigation
Loading bar appears at top of page
Page content is fetched in background
New content replaces current page seamlessly
Redirecting with Navigation
Use CBWIRE's redirect() method with navigation enabled:
Persisting Elements Across Pages
Use Alpine's x-persist to maintain elements like audio/video players:
Preserving Scroll Position
Livewire preserves page scroll by default. For specific elements, use wire:scroll:
JavaScript Hooks
Navigation triggers three lifecycle events:
Manual Navigation
Trigger navigation programmatically:
Event Listeners
Handle persistent event listeners properly:
Analytics Integration
Ensure analytics track navigation properly:
Script Handling
Control script execution across navigations:
Progress Bar Customization
Configure the loading indicator:
Custom Loader Example
Create a custom progress indicator:
wire:navigate often provides 2x faster page loads and creates a JavaScript SPA-like experience while maintaining server-side rendering benefits.
Prefetching with .hover increases server usage. Use judiciously on high-traffic sites.
Was this helpful?