建立 Inertia 回應很簡單。首先,在您的控制器或路由中調用 Inertia::render()
方法,並提供您想要渲染的JavaScript 頁面組件名稱,以及該頁面的任何屬性 (資料)。
在下面的範例中,我們將傳遞一個單一屬性 (event
),其中包含四個屬性 (id
、title
、start_date
和 description
) 給 Event/Show
頁面組件。
use Inertia\Inertia;
class EventsController extends Controller
{
public function show(Event $event)
{
return Inertia::render('Event/Show', [
'event' => $event->only(
'id',
'title',
'start_date',
'description'
),
]);
// Alternatively, you can use the inertia() helper...
return inertia('Event/Show', [
'event' => $event->only(
'id',
'title',
'start_date',
'description'
),
]);
}
}
在某些情況下,您可能希望在應用程式的根 Blade 範本中存取您的屬性資料。例如,您可能想要新增 meta 描述標籤、Twitter 卡片 meta 標籤或 Facebook Open Graph meta 標籤。您可以透過 $page
變數存取此資料。
<meta name="twitter:title" content="{{ $page['props']['event']->title }}">
有時您甚至可能想將資料提供給不會傳送到 JavaScript 頁面/組件的根範本。這可以透過調用 withViewData
方法來完成。
return Inertia::render('Event', ['event' => $event])
->withViewData(['meta' => $event->meta]);
調用 withViewData
方法後,您可以像存取 Blade 範本變數一樣存取定義的資料。
<meta name="description" content="{{ $meta }}">
為了啟用客戶端歷史導覽,所有 Inertia 伺服器回應都會儲存在瀏覽器的歷史記錄狀態中。但是,請記住,某些瀏覽器對歷史記錄狀態中可以儲存多少資料有大小限制。
例如,Firefox 的大小限制為 640k 個字元,如果超出此限制,則會拋出 NS_ERROR_ILLEGAL_VALUE
錯誤。通常,這比您在建置應用程式時實際需要的資料量還要多得多。