Laravel 8+Vue 3 登录后不使用vue-router跳转到仪表盘问题咨询
问题根因
- 你没有使用vue-router,
this.$router.push是vue-router提供的专属路由跳转方法,自然无法调用生效 - Laravel的
api路由组默认不开启session中间件,你在API接口中调用Auth::attempt生成的登录状态不会存入session,跳转到走web中间件的仪表盘页面时,系统会判定为未登录,直接重定向回登录页
解决步骤
1. 替换Vue端跳转逻辑
使用浏览器原生跳转方法代替vue-router的跳转方法,替换Vue组件中submit方法里的跳转逻辑:
submit() { axios.post('/login', this.fields) .then(response => { if (response.data.status === 200) { this.fields = {}; this.errors = {}; this.success = true; // 这里替换为原生跳转,加1秒延迟用于展示成功提示,不需要延迟可以去掉setTimeout setTimeout(() => { window.location.href = '/dashboard'; }, 1000); } }).catch(error => { if (error.response.status === 422) { this.errors = error.response.data.errors; } }); }
2. 修复session同步问题
因为API路由无session的特性不符合你的场景,直接将登录接口迁移到web路由组即可:
- 先删除api.php中定义的登录路由
- 在web.php中添加登录POST路由:
// 放在guest中间件组里即可 Route::group(['middleware' => 'guest'], function () { Route::get('/login', [AuthLoginCreate::class, 'create'])->name('login'); // 新增登录POST路由 Route::post('/login', [ApiAuthLoginStore::class, 'store'])->name('login.store'); });
3. 可选校验
确认AuthDashboardIndex控制器的index方法正常返回仪表盘的Blade视图,示例代码参考:
public function index() { return view('dashboard'); }
内容的提问来源于stack exchange,提问作者Mohsen
相关产品推荐
相关产品推荐

