Vuejs configuration: using a global variable?

It seems dumb, but I have the setup as follows:

in config/index.js:

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

then src/app.jsI have:

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;

Then in src/components/home.vueI have a script block that uses it like this:

<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>

This works, but it seems like a bad idea to use windowto process the application configuration. What is the more canonical approach here?

+4
source share
2 answers

Import it.

<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>

Or just the location.

<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>
+3
source

PROD: config/prod.env.jsaddVAR='"value"'

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

Dev: config/dev.env.jsaddVAR='"value"'

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

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

Variable yuor will be available in process.env.API_LOCATIONor process.env.VAR_NAME

0

Source: https://habr.com/ru/post/1680080/


All Articles