vue

What is the best way to declare global variable in VueJS


In this article, you will learn about how to declare global variables in VueJs.

While working with VueJS, you need to declare a global variable so that you can access it from anywhere in the project. This is quite useful to declare a global variable otherwise you need to declare it from each file where you need to use it. Let’s see the below code example of how you can set a global variable in VueJS;

Vue.prototype.$hostname = 'your variable name'

Suppose, you want to set a localhost on a specific port number. But if you do not declare it as a global variable you need to define it each file. Let’s see how you can define it as a global variable in VueJS.

Vue.prototype.$hostname = '<http://localhost:5000>'

This will set $hostname as a global variable and make it available for all vue instances and you can access it like this :

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

You can also defined this $hosname prototype according to vue production tip variable so that it can change automatically change from development to production based on you command. See the code below of how you can do this :

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

If you are aware of that you only need few base variables and these variables does not need to be modified then you may use ES6 imports/exports. See the below code example:

// In your config.js file
export default {
   hostname: 'hostname'
}

// In your .vue file
import config from 'config.js'

console.log(config.hostname)

This is all about the ways you can declare a global variable in the best way in VueJS. You may get an overview of declaring a global variable in VueJS from this article.


Share on social media

//