刷新时 vuejs 模板不起作用,我只得到 json 数据、Vuejs 和 Laravel

On refresh vuejs template is not working and I get just json Data, Vuejs and Laravel

我有一条路线,当我刷新页面时,我只获得该页面的 JSON 信息。 (仅在刷新 F5 时)。其余路线没问题。我不确定我做错了什么。

web.php

 Route::get('/persons', 'MyController@index');
    Route::post('/record/{personId?}', 'MyController@create');  // this is the one that don't work on refresh
    Route::get('/record/{id}', 'MyController@getRecord');
    Route::delete('/record/{id}', 'MyController@destroy');
    Route::get('/lookups', 'LkpController@index');
    Route::post('/validate', 'MyController@getValidation');

//Routes for VueJs
    Route::get('/{any}', function () {
        return view('welcome');
    })->where('any','^(?!api).*$')->name('home');

router.js

const routes = [
    {
        path: "/",
        name: "Home",
        component: Home,
        meta: { requiresAuth: true }
    },
    {
        path: "/record",
        name: "Record",
        component: Record,
        meta: { requiresAuth: true }
    },
    {
        path: "/record/:id",
        name: "View Record",
        component: require ('./components/AddPerson').default,
        meta: { requiresAuth: true }
    }
];

const router = new VueRouter({
    mode: "history",
    base: process.env.BASE_URL,
    routes
});

export default router;

问题是您将所有路由放在 web.php 中,并且 Vue SPA 的路由与 Laravel 应用程序相同。

你应该将你的 API 路由放在你的 web/api.php 文件中,这样它们将自动以 'api' 路由作为前缀。

返回JSON数据的路由不是你指出的那个,是下一个:

Route::get('/record/{id}', 'MyController@getRecord'); // this is the one that don't work on refresh

这是因为您的 Vue 路由器指向完全相同的路由:

{
    path: "/record/:id",
    name: "View Record",
    component: require ('./components/AddPerson').default,
    meta: { requiresAuth: true }
}

两条路线都指向 yourwebsite.com/record/{id},但在刷新时,您向 Laravel 应用程序发出全新请求,这意味着您不再在 Vue 应用程序中,您的浏览器将加载任何内容 Laravel 将首先告诉他们,在这种情况下它将是 routes/web.php 文件中的第一条路线:

Route::get('/record/{id}', 'MyController@getRecord');

Edit: This is how you should do it if you cannot use API routes due to authentication:

你必须确保你的 Vue 路由器和你的 Laravel 路由之间没有重复的路由,你可以在它们前面加上对你有意义的东西。

Route::prefix('prefix')->group(function () {
    Route::get('/persons', 'MyController@index');
    Route::post('/record/{personId?}', 'MyController@create');
    Route::get('/record/{id}', 'MyController@getRecord');
    Route::delete('/record/{id}', 'MyController@destroy');
    Route::get('/lookups', 'LkpController@index');
    Route::post('/validate', 'MyController@getValidation');
});

//Routes for VueJs
    Route::get('/{any}', function () {
        return view('welcome');
    })->where('any','^(?!api).*$')->name('home');

在此示例中,您遇到问题的路由现在将以 'prefix' yourwebsite.com/prefix/record/{id} 为前缀,您可以将其更改为您需要的任何内容。