How to declare global variable in Vue JS

featured Image

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:

<script>
  beforeCreate: function() {
    console.log(this.$variableName)
  }
</script>

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),
}).$mount('#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.

Related Posts

featured Image

How to add common header and footer in vuejs.

Here, in this article, we will learn how to add a common header and footer component in our vuejs application. In general, we always have the same header and footer…

Read more
featured Image

How to call a function in VUE template?

Here, we will learn on how to call a function in vue template. First, we have to define the function in the methods. and then we can use an event…

Read more
featured Image

How to redirect to external url in vue

Here, we will learn how to redirect to an external URL in vuejs application. Page Navigation is one of the basic features of a website. It helps us to navigate…

Read more