[英]Accessing Laravel's .env variables inside Inertia.js Vue files
我從慣性 Laravel 示例開始https://github.com/drehimself/inertia-example
這只不過是 Laravel 和 Vue 在一個整體代碼庫中,使用 Inertia.js: https : //github.com/inertiajs/inertia-laravel https://github.com/inertiajs/inertia-vue
我試圖在我的 .vue 組件文件中訪問 Laravel 的 .env 變量
.env 文件:
APP_NAME=ABC
在 app\\Providers\\AppServiceProvider.php 中:
public function register()
{
Inertia::share('appName', env('APP_NAME'));
}
在 resources\\js\\Home.vue 組件中:
<template>
<div>
<span class="tw-text-left">{{ appName }}</span>
</div>
</template>
<script>
export default {
props: [
"appName",
]
}
</script>
在我的 vue 控制台中,appName 顯示為空白。 它應該顯示“ABC”,但沒有。 這里發生了什么,以及我如何訪問我所有的 env 變量,理想情況下不通過控制器傳遞所有內容,這似乎不是很有效?
我終於讓它工作了。 以下是感興趣的人的方法:在 AppServiceProvider 中:
Inertia::share(function () {
return [
'app' => [
'name' => config('app.name'),
],
];
});
在你的 vue 文件中:
<template>
<div>
App name: {{ $page.app.name }}
</div>
</template>
第二部分是我所缺少的..我試圖接受 app.name 道具,但缺少 $page。 希望這對某人有幫助!
我知道這有點舊,但我遇到了同樣的問題,上面和網上的方法對我不起作用。 慣性可能會改變什么? 無論如何,我確實讓它工作了。
就像上面一樣,將以下內容添加到 AppServiceProvider 中的 register 方法中:
Inertia::share('appName', config('app.name'));
// I'm using config, but your could use env
然后在您的 Vue 組件中訪問$inertia
變量,如下所示:
{{ $inertia.page.props.appName }}
如果要與視圖共享多個變量,請使用以下命令:
Inertia::share('app', [
'name' => config('app.name'),
'url' => config('app.url'),
]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.