如何使用Inertia向Vue独立侧边组件加载数据?
用Inertia实现独立获取数据的侧边组件
你可以通过以下两种方式实现侧边组件独立获取数据,无需依赖父组件或axios:
方案1:通过router.visit实现无跳转的数据获取
利用Inertia的router.visit方法,通过配置参数避免页面跳转,仅拉取所需数据。这是最贴近你需求的方式,完全基于Inertia生态实现。
组件代码修改:
<script setup> import { ref, onMounted } from 'vue' import { router, usePage } from '@inertiajs/vue3' const labels = ref([]) const page = usePage() onMounted(() => { // 调用后端路由获取数据,配置参数避免页面刷新 router.visit(route('sidebar.labels'), { preserveState: true, // 保留当前页面状态,不重置组件 preserveScroll: true, // 保留滚动位置 only: ['labels'], // 仅请求labels字段,减少数据传输 onSuccess: () => { // 从Inertia的page props中提取数据 labels.value = page.props.labels } }) }) </script> <template> <div v-for="(label, index) in labels" :key="index" v-html="label"></div> </template>
后端配置:
- 控制器方法:返回包含所需数据的Inertia响应(可以绑定任意视图,甚至是空视图,因为我们只需要props)
<?php namespace App\Http\Controllers; use Inertia\Inertia; class SidebarController extends Controller { public function getLabels() { // 这里可以替换为从数据库或其他来源获取数据 $labels = ['Foo', 'Bar']; return Inertia::render('Shared/EmptyView', [ 'labels' => $labels, ]); } }
- 路由定义:添加指向该控制器方法的路由
// web.php use App\Http\Controllers\SidebarController; Route::get('/sidebar/labels', [SidebarController::class, 'getLabels'])->name('sidebar.labels');
方案2:将侧边组件设为独立的Inertia页面,通过惰性加载嵌入
如果你的侧边组件需要在多个页面复用,也可以把它定义为一个独立的Inertia页面,然后用惰性加载的方式嵌入到父页面的<aside>中。
父页面中嵌入组件:
<template> <div class="layout"> <main>...</main> <aside> <InertiaLazy component="Sidebar/Labels" /> </aside> </div> </template>
侧边组件的控制器:
public function showLabels() { $labels = ['Foo', 'Bar']; return Inertia::render('Sidebar/Labels', compact('labels')); }
路由:
Route::get('/sidebar/labels', [SidebarController::class, 'showLabels'])->name('sidebar.labels');
这种方式下,组件会在挂载时自动通过Inertia加载自身数据,无需手动调用API,且完全独立于父组件。
内容的提问来源于stack exchange,提问作者JanBoehmer
相关产品推荐
相关产品推荐

