使用 Laravel 和 Vue 时,通过 Blade Views 将数据传递到 Vue 与使用 Axios 直接传递到 Vue 组件的优缺点是什么?

When using Laravel and Vue, what are the pros and cons of passing data to Vue via Blade Views vs directly to Vue Components with Axios?

目前,我以这种方式将数据从 Laravel 传递到 Vue(通过 MySQL 数据库):

在routes/web.php:

Route::get('/', [MyController::class, 'index']);

在app/Http/Controllers/MyController.php

public function index() {

    $results = Data::all();

    return view('index', compact('results'));

}

在resources/views/index.blade.php:

<div id="app">
    <index-component :results="{{ $results }}" />
</div>

然后在IndexComponent.vue

props: {
    results: { 
        type: Object 
    };
}

这很好用,但由于我的大部分 HTML 都依赖 Vue,所以感觉不自然,几乎像是一种变通方法或 hack。一定有更简单直接的方法吧?

输入 Axios:

在routes/web.php:

Route::view('/', 'index');
Route::get('/indexrequests', [MyController::class, 'indexRequests']);

在app/Http/Controllers/MyController.php:

public function indexRequests() {

    $results = Data::all();

    return response()->json($results);
}

在resources/views/index.blade.php:

<div id="app">
    <index-component />
</div>

在IndexComponent.vue中:

created() {
    this.getResults()
},
data: function() { 
    return {
        results: null,
    }
}, 
methods: {
    getResults() {
          axios
            .get("/indexrequests")
            .then((res) => (this.results = res.data))
            .catch((error) => {});
    }
}
 

这样,Blade View 在初始创建后可以被忽略。 getResults() 方法直接与控制器对话。

我的问题是,费用是多少?如果不使用 Blade Views 传递数据,我会失去什么(如果有的话)?我会遇到可以通过这种方式传递的数据量或类型的限制吗?性能会更好还是更差?有任何安全问题吗?

也许它们在底层是相同的,而我只是没有意识到这一点?

这些方法并不相同,但在这种情况下不会有太多实际差异。为了 SEO 的目的,使用初始数据在服务器端呈现一些标记可能是有益的,但这不会发生在这里。

依靠 API 而不是硬编码数据可以实现更灵活的前端应用程序。

根据硬编码数据的性质和数量,它可能会导致初始渲染速度变慢,但完成渲染速度更快。 prop 中的硬编码数据需要额外注意转义,如果重新渲染父组件,也会导致性能下降。一种常见的方法是将初始数据作为全局变量提供:

<script>
window.myApp = { someData: '{{$results}}' };
</script>
<div id="app">
...

其中 $results 是 JSON 带有转义引号(在本例中为单引号)的数据。