目前,我以這種方式將資料從 Laravel 傳遞到 Vue(通過 MySQL 資料庫):
在路由/web.php 中:
Route::get('/', [MyController::class, 'index']);
在 app/Http/Controllers/MyController.php
public function index() {
$results = Data::all();
return view('index', compact('results'));
}
在資源/視圖/index.blade.php 中:
<div id="app">
<index-component :results="{{ $results }}" />
</div>
然后在 IndexComponent.vue
props: {
results: {
type: Object
};
}
這作業得很好,但由于我的大部分 HTML 都依賴于 Vue,這感覺不自然,幾乎像是一種解決方法或 hack。一定有更簡單更直接的方法嗎?
輸入 Axios:
在路由/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);
}
在資源/視圖/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) => {});
}
}
這樣,刀片視圖在最初創建后可以被忽略。getResults() 方法直接與控制器對話。
我的問題是,代價是什么?如果不使用 Blade Views 傳遞資料,我會失去什么?我是否會遇到可以通過這種方式傳遞的資料數量或型別的限制?性能會以一種或另一種方式變好還是變差?有任何安全問題嗎?
也許它們在引擎蓋下是相同的,而我根本沒有意識到這個事實?
uj5u.com熱心網友回復:
這些方法并不相同,但在這種情況下不會有很多實際差異。出于 SEO 的目的,使用初始資料在服務器端呈現一些標記可能是有益的,但這不會發生在這里。
依靠 API 而不是硬編碼資料會導致更靈活的前端應用程式。
根據硬編碼資料的性質和數量,它可能會導致初始渲染速度變慢,但完整渲染速度會更快。prop 中的硬編碼資料需要額外注意轉義,如果父組件被重新渲染,也會導致性能下降。一種常見的方法是將初始資料作為全域變數提供:
<script>
window.myApp = { someData: '{{$results}}' };
</script>
<div id="app">
...
$results帶轉義引號的 JSON 資料在哪里(在這種情況下是單引號)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/377009.html
標籤:拉拉维尔 Vue.js 公理 laravel-8 laravel-blade
