访问 Inertia.js Vue 文件中 Laravel 的 .env 变量

kp1*_*123 8 inertiajs laravel vue.js laravel-5 vuejs2

我从 Inertia 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
Run Code Online (Sandbox Code Playgroud)

在应用程序\Providers\AppServiceProvider.php中:

APP_NAME=ABC
Run Code Online (Sandbox Code Playgroud)

在 resources\js\Home.vue 组件中:

<template>
  <div>
        <span class="tw-text-left">{{ appName }}</span>
  </div>
</template>

<script>
export default {
  props: [
    "appName",
 ]
}
</script>
Run Code Online (Sandbox Code Playgroud)

在我的 vue 控制台中,appName 显示为空白。它应该显示“ABC”,但没有。这里发生了什么,以及我如何访问所有环境变量,理想情况下不通过控制器传递所有内容,这似乎不是很有效?

alm*_*125 6

我知道这有点老了,但我遇到了同样的问题,并且网上和网上的方法对我不起作用。惯性可能会改变一些东西吗?不管怎样,我确实让它工作了。

就像上面一样,将以下内容添加到 AppServiceProvider 中的注册方法中:

Inertia::share('appName', config('app.name'));
// I'm using config, but your could use env
Run Code Online (Sandbox Code Playgroud)

然后在你的 Vue 组件中访问$inertia变量,如下所示:

{{ $inertia.page.props.appName }}
Run Code Online (Sandbox Code Playgroud)


kp1*_*123 5

我终于让它工作了。对于那些感兴趣的人来说,方法如下:在 AppServiceProvider 中:

        Inertia::share(function () {
            return [
                'app' => [
                    'name' => config('app.name'),
                ],
            ];
        });
Run Code Online (Sandbox Code Playgroud)

在你的 vue 文件中:

<template>
<div>
App name: {{ $page.app.name }}
</div>
</template>
Run Code Online (Sandbox Code Playgroud)

第二部分是我所缺少的。我试图接受 app.name 属性,但缺少 $page。希望这对某人有帮助!