How to declare global variable in Vue JS

In this short tutorial, we will see how to declare a global variable in vuejs with examples.

Sometimes while working on any project we need to declare some global properties or variables so that we can access the value from anywhere in our projects.

In VueJs, it's quite useful to declare global variables so that we don't have to declare them every time when we use them in our components.

Declare Global Variable in Vue 2

In Vue 2, we can declare a global variable using Vue.prototype syntax, like this

Vue.prototype.$variableName = 'My App'

The variable $variableName is available in all instances, so you can even access it, even before creation.

To access the variable in any component in Vue, we can use this.$variableName like this:

  beforeCreate: function() {

You can see My App in your console.

The $ sign is a Vue convention that is used for properties that are available to all instances. It is used to avoid any conflicts with any defined data or methods in the project.

Example of declaring a global variable in a real project.

Let's say, we want the hostname to be available in all components of our project.

To do so, open your main.js file and declare and set the value, like this.

In main.js

import Vue from 'vue'
import App from './App.vue'

// global variable
Vue.prototype.$hostname = '<http://localhost:8080>'

new Vue({
  render: h => h(App),

Now you can access the hostname, from anywhere in your project using this.$hostname .

Declare Global Variable in Vue 3

In Vue 3, we can set a global property using this syntax:

const app = Vue.createApp({})
app.config.globalProperties.$hostname = 'http://localhost:8080'

The $hostname is our variable and to access the property we can use this of any component instance.

mounted() {
    console.log(this.$hostname) // 'http://localhost:8080'

In Vue 3, if the global variable conflicts with the component variable then, the component's own variable is given a higher priority.

💾 Recommended Articles