How to import a config file into Vue.JS+Vuex

Viewed 9710

I'm setting configs in my main.js file before calling Vue :

Vue.prototype.$api_url = process.env.NODE_ENV === 'production' ? 'https://api.xxx.com' : 'https://yyy.test:8443'

It works if I access this.$api_url in any Vue file.

But in store.js (Vuex), it's another Vue Instance that is rendered, so I can't access this.$api_url.

What about setting the configs in a file and Vue.use(configs.js) ?

What should I do inside the configs file in order to get its variables in main.js/store.js ?

Thank you.

1 Answers

Make a standalone config.js file and export your config object from that file. And import config where ever you need config. You can also assign the same config to Vue's prototype if you want that to be provided in all Vue components.

Update:

So here is how you can do this:

In your config.js

let config;

if (process.env.NODE_ENV === "production") {
  config = {
    $api_url: "https://api.xxx.com",
    timeoutDuration: 30000,
    someOtherProps: 'xyz'
  };
} else {
  config = {
    $api_url: "https://yyy.test:8443",
    timeoutDuration: 1000,
    someOtherProps: 'abc'
  };
}

export { config }

In your main.js

import { config } from 'config';

Vue.prototype.appConfig = config

use this.appConfig.$api_url whatever way you want to use in .vue files

In your store.js

import { config } from 'config';

use config.$api_url whatever way you want to use

Related