【问题标题】:privateRuntimeConfig values are undefined under pluginsprivateRuntimeConfig 值在插件下未定义
【发布时间】:2021-02-10 08:20:14
【问题描述】:

历史,我想知道如何在plugins 下的 Nuxt 中使用 privateRuntimeConfig。 我想运行传递 env 的 firebase 初始化函数,但 $config 似乎未定义。 我错过了什么吗?

// nuxt.config.js

privateRuntimeConfig: {
  firebase: {
    apiKey: process.env.apiKey,
    authDomain: process.env.authDomain,
    databaseURL: process.env.databaseURL,
    projectId: process.env.projectId,
    storageBucket: process.env.storageBucket,
    messagingSenderId: process.env.messagingSenderId
  }
}

// plugins/firebase.ts

import firebase from 'firebase';

if (!firebase.apps.length) {
  firebase.initializeApp($config); // error: $config is undefined
}

export default firebase($config);

【问题讨论】:

  • 你为什么期望它被定义?你认为它应该有什么价值?
  • 我认为$config 包含在nuxt.config.js 中privateRuntimeConfig 下定义的值。

标签: firebase vue.js nuxt.js


【解决方案1】:

您可以从 nuxt 的服务器端生命周期钩子访问 privateRuntimeConfig 变量:如 NuxtServerInit、Validate()、asyncData() 或 fetch(context)

nuxt-生命周期:https://nuxtjs.org/docs/2.x/concepts/nuxt-lifecycle

如果私有和公共运行时配置具有相同的值,则私有运行时会覆盖公共运行时。

让我用一个简单的代码解释一下;

nuxt.config.js

...
publicRuntimeConfig: {
  API_KEY: '1245',
},
privateRuntimeConfig: {
  API_KEY: 'AIzaSyAxwq', //Real API-Key
},
...

plugins/helpers.js

import Vue from 'vue';

export default function({ app }, inject) {

  const helpers = {
    getApiKey() {
      return app.$config.API_KEY;
    }
  };
  inject('helpers', helpers);
}

pages/test.vue

...
<script>
  export default {
    asyncData(context) {
      console.log(context.$helpers.getApiKey()) --> displays: AIzaSyAxwq
    },
    created() {
      console.log(this.$helpers.getApiKey()) --> displays: 12345
    }
  }
</script>
...

【讨论】:

  • 这个答案包含了很多内容。谢谢!
猜你喜欢
  • 2020-12-20
  • 2017-07-26
  • 1970-01-01
  • 2021-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多