Laravel Vue Inertia Jetstream实现仅登录用户可见区块
Laravel Jetstream + Inertia + Vue 登录状态全局管理方案
1. 全局共享登录用户信息(Inertia 官方推荐方案)
Jetstream 搭配 Inertia 时,不需要手动用 Provide/Inject 维护登录状态,Inertia 内置了全局数据共享能力,能让所有 Vue 组件直接获取用户认证信息。
在后端 app/Providers/AppServiceProvider.php 的 boot 方法中添加全局共享逻辑:
use Inertia\Inertia; use Illuminate\Support\Facades\Auth; public function boot() { Inertia::share([ 'auth' => function () { return [ 'user' => Auth::user() ? [ 'id' => Auth::user()->id, 'name' => Auth::user()->name, 'email' => Auth::user()->email // 按需添加其他用户字段 ] : null, ]; }, ]); }
这样所有 Inertia 渲染的页面和组件,都能直接访问 $page.props.auth.user 获取登录用户信息,无需在每个路由单独传递。
2. 在复用组件中控制元素显示
以 Navbar 组件为例,直接通过全局共享的用户信息判断登录状态:
<template> <nav class="bg-white shadow dark:bg-gray-800"> <!-- 未登录状态 --> <div v-if="!$page.props.auth.user"> <Link :href="route('login')">登录</Link> <Link :href="route('register')">注册</Link> </div> <!-- 已登录状态 --> <div v-else> <span>欢迎,{{ $page.props.auth.user.name }}</span> <form @submit.prevent="handleLogout"> <button type="submit">退出登录</button> </form> </div> </nav> </template> <script setup> import { Link, router } from '@inertiajs/inertia-vue3'; const handleLogout = () => { router.post(route('logout')); }; </script>
3. 简化 Dashboard 路由与组件
因为已经全局共享用户信息,Dashboard 路由无需单独传递 user 参数:
Route::middleware([ 'auth:sanctum', config('jetstream.auth_session'), 'verified', ])->group(function () { Route::get('/dashboard', function () { return Inertia::render('Dashboard'); })->name('dashboard'); });
Dashboard.vue 中也可以删除多余的 props 定义,直接依赖全局共享的 auth 数据。
4. 多视图复用组件的权限控制
对于 Portfolio 这类跨页面复用的组件,直接在组件内判断登录状态即可:
<template> <div class="portfolio"> <h2>作品集展示</h2> <!-- 仅登录用户可见的操作按钮 --> <button v-if="$page.props.auth.user" class="edit-btn">编辑我的作品集</button> <!-- 公共展示内容 --> <div class="portfolio-items">...</div> </div> </template>
内容的提问来源于stack exchange,提问作者Marco Rifo
相关产品推荐
相关产品推荐

