【问题标题】:Unable to use API key as env variable with Butter CMS library inside asyncData()无法使用 API 密钥作为环境变量与 asyncData() 中的 Butter CMS 库
【发布时间】:2018-11-11 22:58:52
【问题描述】:

我最近将 my site 从 Drupal 转换为 Vue,它目前作为常规 Vue 应用程序运行。出于 SEO(和其他原因),我正在努力将其转换为使用 Nuxt,但我无法弄清楚如何将私有 API 密钥设置为环境变量并将其用于带有 Butter 库和 @ 的组件中987654322@。使用Butter docs for Vue,我让它在SPA 中运行良好,但我无法在Nuxt 中使用相同的东西。

在我的SPA中,我只是将API_KEY添加到dev.env.js,然后我在buttercms.js中有这两行:

import Butter from 'buttercms'
export const butter = Butter(process.env.API_KEY)

然后在我的组件中:

<script>
import { butter } from "@/buttercms";
...
methods: {
  getPost() {
  butter.post.retrieve(this.$route.params.slug)
    .then(res => {
       this.post = res.data;
    })
    .catch(res => {
      console.log(res);
    });
  }
},

效果很好。在 Nuxt 中,我将我的 API 密钥设置为 nuxt.config.js,如下所示:

env: {
  API_KEY: process.env.API_KEY || '1234567890'
},

buttercms.js 的内容与上面列出的相同,然后在我的组件中:

<script>
import { butter } from "buttercms";
export default {
  asyncData(context) {
    return butter.page
      .retrieve("static_page", "about-smga")
      .then(res => {
        console.log(res.data.data);
        return {
          page: res.data.data
        };
      })
      .catch(res => {
        console.log(res);
      });
  },
...
</script>

但是,当我运行它时,我收到一条错误消息 Cannot read property 'page' of undefined,它告诉我 Butter 库没有被使用。显然我做错了什么,但我不确定是什么。我需要更改哪些内容才能在我的asyncData() 通话中使用butter

【问题讨论】:

    标签: javascript asynchronous vue.js environment-variables nuxt.js


    【解决方案1】:

    您正在从组件中的 buttercms 模块导入黄油类。但它没有初始化。您可以将初始化放入 plugins/buttercms.js 并将其添加到 nuxt.config 到插件部分。

    import Butter from 'buttercms'
    
    export default (ctx, inject) => {
      inject('butter', Butter(process.env.API_KEY))
    }
    

    然后你可以通过 this.$butter 在你的组件中引用初始化实例

    【讨论】:

    • 好吧,因为我在 asyncData() 中调用 Butter,所以我不能使用 this,因为它还不可用,如果我尝试 $黄油 或保持原样,我收到一个错误,即未定义黄油。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-09
    • 2020-12-06
    • 2021-06-10
    • 2016-10-12
    • 2020-06-30
    相关资源
    最近更新 更多