How to declare global variable in Vue JS
Find out how to set and declare global variables in vue js 2 and vue 3 to access the variable any where in the project.
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.
<u>In main.js</u>
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
Easy Way to use localStorage with Vue
Short article on how to use local storage with Vue and learn saving and storing data in local storage with the setItem() and getItem() methods.
Force update Vue to Reload/Rerender component
Short tutorial on how to correctly force update Vue.js component to reload or rerender. The component is reinitialized without having to do a browser refresh.
Set and get cookies in a browser in Vue App
Find out how to set and get cookies in a browser for your webpage in Vue using vue-cookies package.
Save vuex state after page refresh in Vue App
Short tutorial on how to save (or persist) data in a vue application using Vuex and vuex-persist npm package.
