How to create global variable in Vuejs

As you need to create a global variable and access that variable in your every component, for example, like you have a url “http://localhost:3000” and want to set in localhost variable 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.

Goto your app.js file where you initialize the Vue

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

how to use a global variable in your components

export default {
   name: 'your_component_name',
   data(){
      return {
         //ussing global defined variable
         hostName: this.$hostname
      }
   },
   
}

 

 

Was this post helpful?
Let us know if you liked the post. That’s the only way we can improve.
Yes0
No0
Harinder Singh

Harinder Singh

My name is Harinder Singh and I specialize in Software industry. I consider myself as a life learner. I love learning new concepts, embracing new ideas and reading and searching for innovation.