首页 > 解决方案 > 如何在 laravel 应用程序中访问 vue.js api 密钥

问题描述

您好,我正在尝试从此代码中访问位于 .env 文件中的 youtube api 密钥:

<template>
   <div class="YoutubeDash__wrapper">
      <video-group :videos="videos"></video-group>
   </div>
</template>

<script>
  import VideoGroup from './VideoGroup.vue';
  import Search from './Search';

  export default {
    components: {
      VideoGroup
    },
    created(){
      Search({
        apiKey: process.env.VUE_APP_SECRET,
        term: 'laravel repo'
      }, response => this.videos = response);
    },

    data(){
      return {
        videos: null
      }
    }
  }
</script>

根据使用 env variables with vue.js的文档。一切似乎都是正确的。在我的 .env 文件中,我说:VUE_APP_SECRET=xxxxxxxxxxxxxxx,我在这里缺少什么?

我收到此错误消息:

app.js:37809 Error: YouTube search would require a key

欢迎任何提示!非常感谢!

标签: laravelvue.js

解决方案


我更喜欢从这个过程中排除 laravel-mix。
通常,在我的刀片入口点中,我使用元标记:

<meta name="myVal" content="{{ config('<any-config-key>') }}">

<any-config-key>可以是任何 laravel 配置键,包括从.env.
然后,在我的 javascript 中,我执行以下操作:

const setVueGlobal = (metaHeaderName, vueGlobalName) => {
    let value = document.head.querySelector('meta[name="' + metaHeaderName + '"]').content;
    if (!value) {
        console.error('some error msg');
        return null;
    }

    Vue.prototype[vueGlobalName] = value;
    return value;
};

setVueGlobal('myVal', '$myVal');

最后,访问使用this.$myVal


推荐阅读