What is the best way to declare global variable in Vue.js?

Dmitry Bubnenkov picture Dmitry Bubnenkov · May 21, 2016 · Viewed 103.2k times · Source

I need access to my hostname variable in every component.

Is it a good idea to put it inside data?

Am I right in understanding that if I do so, I will able to call it everywhere by this.hostname?

Answer

Josiel Faleiros picture Josiel Faleiros · Feb 21, 2018

As you need access to your hostname variable in every component, and to change it to localhost while in development mode, or to production hostname when in production mode, you can define this variable in the prototype.

Like this:

Vue.prototype.$hostname = 'http://localhost:3000'

And $hostname will be available in all Vue instances:

new Vue({
  beforeCreate: function () {
    console.log(this.$hostname)
  }
})

In my case, to automatically change from development to production, I've defined the $hostname prototype according to a Vue production tip variable in the file where I instantiated the Vue.

Like this:

Vue.config.productionTip = false
Vue.prototype.$hostname = (Vue.config.productionTip) ? 'https://hostname' : 'http://localhost:3000'

An example can be found in the docs: Documentation on Adding Instance Properties

More about production tip config can be found here:

Vue documentation for production tip