在Vue中添加外部配置文件进行部署? [英] Add an external configuration file in Vue for deployment?

查看:69
本文介绍了在Vue中添加外部配置文件进行部署?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须调用 API (json-server) 来检索数据,以便在我的 Vue 应用程序中填充下拉列表.我想创建一个外部配置文件,而不是在应用程序中进行硬编码,我可以在其中放置任何链接并最终放置用于部署的服务器详细信息.目前,我有这个,但由于某种原因,当我在我的 vue 组件中引用 Key 时,它说它未定义.我不确定我哪里出错了.

I have to call an API (json-server) to retrieve data in order to populate my dropdowns within my Vue application. Instead of hard-coding within the app, I want to create an external configuration file where I can put any links and eventually put server details for deployment. Currently, I have this but for some reason when I reference the Key in my vue component, it says it undefined. I'm not sure where I'm going wrong.

    /public/config.json
    
   {
     "API_URL": "localhost:3000"
   }

以下是 main.js 文件的相关部分:

Here is the relevant parts of the main.js file:

    /main.js

    fetch(process.env.BASE_URL+ "config.json")
    .then((json) => {
    json().then((config) => {
    Vue.prototype.$config = config
    new Vue({
     router,
     store,
     render: (h) => h(App)
   }).$mount("#app")
  })
 })

在我的 Vue 组件中,我试图像这样引用它,但它显示为未定义.

In my Vue component, I'm trying to reference it like this, but it is showing up as undefined.

      <script>
      export default {
      mounted() {
        fetch(this.$config.API_URL)
            .then(res => res.json())
            .then(data => this.mailboxes = data)
            .catch(err => console.log(err.message))
      }
      }

      </script>

如果有其他方法可以解决这个问题,请告诉我.

If there is another way to go about this please let me know.

推荐答案

如果您希望应用构建一次并在具有不同配置的多台服务器上使用相同的包,这是正确的方法.注释中建议的 ENV 变量 不起作用,因为这些值是烘焙的"在"到捆绑包...

If you want the app build once and use same bundle on multiple servers with different configuration, this is right way to do it. ENV variables suggested in comments wont work as the values are "baked in" to the bundle...

然而,您以错误的方式使用 fetch.fetch 返回 response正在尝试调用而不是调用 response.json()

However you are using fetch in a wrong way. fetch returns response which you are trying to call instead of calling response.json()

fetch(process.env.BASE_URL+ "config.json")
  .then((response) => response.json())
  .then((config) => {
    Vue.prototype.$config = config
    new Vue({
      router,
      store,
      render: (h) => h(App)
    }).$mount("#app")
  })

这篇关于在Vue中添加外部配置文件进行部署?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆