vuejs 配置:使用全局变量?

新手上路,请多包涵

这看起来很愚蠢,但我是这样设置的:

config/index.js 中:

 module.exports = {
    API_LOCATION: 'http://localhost:8080/api/'
}

然后在 src/app.js 我有:

 import Vue from 'vue'
import VueRouter from 'vue-router'
import VueResource from 'vue-resource';

Vue.use(VueRouter);
Vue.use(VueResource);

const App = require("./app.vue");
const home = require("./components/home.vue");
const config = require('../config');
window.config = config;

然后在 src/components/home.vue 中,我有一个像这样使用它的脚本块:

 <script>
    module.exports = {
        data: function() {
            return {
                obj: null
            }
        },
        created: function() {
            this.$http.get(config.API_LOCAITON + '/call').then(res => {
                // Do some business
            }, res => {
                // Handle some error
            });
        }
    }
</script>

这行得通,但我觉得使用 window 来处理应用程序配置是个坏主意。这里更规范的方法是什么?

原文由 Wells 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 417
2 个回答

导入它。

 <script>
    import config from "../config"

    module.exports = {
        data: function() {
            return {
                obj: null
            }
        },
        created: function() {
            this.$http.get(config.API_LOCATION + '/call').then(res => {
                // Do some business
            }, res => {
                // Handle some error
            });
        }
    }
</script>

或者只是位置。

 <script>
    import { API_LOCATION } from "../config"

    module.exports = {
        data: function() {
            return {
                obj: null
            }
        },
        created: function() {
            this.$http.get(API_LOCATION + '/call').then(res => {
                // Do some business
            }, res => {
                // Handle some error
            });
        }
    }
</script>

原文由 Bert 发布,翻译遵循 CC BY-SA 3.0 许可协议

产品: config/prod.env.js 附加你的 VAR='"value"'

 'use strict'
module.exports = {
  NODE_ENV: '"production"',
  API_LOCATION: '"https://production URL"'
}

开发: config/dev.env.js 附加你的 VAR='"value"'

 'use strict'
const merge = require('webpack-merge')
const prodEnv = require('./prod.env')

module.exports = merge(prodEnv, {
  NODE_ENV: '"development"',
  API_LOCATION: '"http://localhost"'
})

您的变量将在 process.env.API_LOCATIONprocess.env.VAR_NAME 中可用

原文由 erajuan 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题