vuejs配置:使用全局变量?

Wel*_*lls 8 javascript node.js vue.js

这看起来很愚蠢,但我设置如下:

config/index.js:

module.exports = {
    API_LOCATION: 'http://localhost:8080/api/'
}
Run Code Online (Sandbox Code Playgroud)

然后在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;
Run Code Online (Sandbox Code Playgroud)

然后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>
Run Code Online (Sandbox Code Playgroud)

这有效,但是使用它window来处理应用程序配置是一个坏主意.这里的规范方法是什么?

Ber*_*ert 9

导入它.

<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>
Run Code Online (Sandbox Code Playgroud)

或者只是位置.

<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>
Run Code Online (Sandbox Code Playgroud)


era*_*uan 5

PROD:config/prod.env.js附加您的VAR='"value"'

'use strict'
module.exports = {
  NODE_ENV: '"production"',
  API_LOCATION: '"https://production URL"'
}
Run Code Online (Sandbox Code Playgroud)

开发人员: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"'
})
Run Code Online (Sandbox Code Playgroud)

您的变量将在process.env.API_LOCATIONprocess.env.VAR_NAME