我正在開發一個使用Vue2,VueRouter和Laravel 5.4的項目。這是一個單頁面應用程序。用於API認證的Laravel Passport(來自我的Vue組件的AXIOS調用)。SPA,中間件和VueRouter
大多數應用程序從一個刀片文件(像這樣)服務:
<?php
//styling and the like
//...
//components being loaded here
<router-view></router-view>
//pull in the app.js file with vue router instantiation and routes
<script src="..."></script>
所有組件和航線在app.js文件中定義的,就是在這個文件中拉出。
通過此刀片文件服務的組件都需要身份驗證;用戶必須登錄並註冊。
但是,應用程序將有一個頁面,非註冊用戶可以訪問該頁面。任何具有該URL的人都可以訪問該頁面;但是,在給予訪問頁面之前,他們需要輸入安全密碼。
該頁面基本上是用戶填寫並提交的表單。它還會事先從數據庫中提取一些數據,以在頁面上填充一些細節。
我還沒有着手做這種性質的任何事情,並且無法找到如何這樣做的例子。雖然我對如何解決這個問題有一些想法,但這是我的最佳猜測:
- 創建一個新的JS文件,它將託管一個新的路由器。
- 創建一個新的刀片文件,該文件將承載
router-view element
。它將拉入新創建的JS文件。 - 將新創建的刀片文件添加到
web.php
文件;創建中間件,該中間件將攔截任何嘗試訪問URLtest/{id}
。如果中間件檢查成功,並且用戶輸入有效的密碼,則中間件將傳遞請求以查看資源。否則,一個錯誤的重定向。
web.php文件:
//Route for those people who are taking a test
Route::get('/test/{id}', '[email protected]');
//The authenticate view
Route::get('/authenticate/{id}', '[email protected]')
->name('authenticate')
->middleware('auth.test');
測試控制器文件:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Test;
class TestController extends Controller
{
public function serveTest(Request $request) {
return View('layouts.test');
}
public function serveAuthenticate() {
return View('authenticate');
}
}
中間件:
<?php
namespace App\Http\Middleware;
use Closure;
use App\Test;
class verifyTestAccess {
public function handle($request, Closure $next) {
//Calculate some conditions here
//...
//Direct user to the authentication view if some condition is true
if($hasPasscode) {
return redirect()->route('authenticate', ['id' => $request->route('id')]);
}
//Let user access resource since it must not be password protected
return $next($request);
}
}
新的刀片服務器文件:
<?php
//Load the one component
<router-view></router-view>
//pull in the protectedPage.js file with vue router instantiation and routes
//this is a different file than in the first blade view
<script src="..."></script>
這是一個很好的方法嗎?我想這種方法存在一些問題,並且創建一個vue-router來拉入一個組件是不理想的。