【发布时间】:2017-06-21 22:41:42
【问题描述】:
我正在开发一个使用 Vue2、VueRouter 和 Laravel 5.4 的项目。它是一个单页应用程序。用于 API 身份验证的 Laravel Passport(来自我的 Vue 组件的 AXIOS 调用)。
应用程序的大部分内容来自一个刀片文件(类似这样):
<?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}', 'TestController@serveTest');
//The authenticate view
Route::get('/authenticate/{id}', 'TestController@serveAuthenticate')
->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 来拉入一个组件并不是最佳选择。
【问题讨论】:
标签: laravel-5 single-page-application vuejs2 vue-router