How to define the global variable in VueJS?May 11, 2022
Hi Friends 👋,
Welcome To SortoutCode! ❤️
Today, I am going to show you How do you define the global variable in VueJS.
A global variable is a variable that is declared in the global scope in other words, a variable that is accessible from all other scopes.
Table of Content
- Setup the Vue (Optional)
- Define globle verible
- Access the global variable
Let’s start the today’s tutorial How do I define the global variable in VueJS.
While working on the Vue project, I need to define the global variable so I can access that variable in my project from anywhere. I am defining the variable once and using the variable multiple times in my project. To define the global variable,
Step 1: Setup the Vue (Optional)
First, we have to install the Vue project, I had installed the vueJS in my system. If you haven’t installed or have any problem with installation you can follow this article, it will show you step by step process of installation. How to Install the VueJS project?
Step 2: Define globle verible
I am defining the global variable using the
import Vue from "vue"; // declare global variable Vue.prototype.$website = "sortoutcode.com";
In the above example, we are using this syntex
Vue.prototype, for variable
$website is your variable name. ’$’ is the very important part, $ is a convention Vue uses for properties that are available to all instances. This avoids conflicts with any defined data, computed properties, or methods.
Step 3: Access the global variable
So when you want to use a global variable in your components, you have to use the
this keyword and the variable name.For example ‘$verible_name’.
// for accessing the global variable this.$website; // sortoutcode.com
For now, let’s check the output.
All the best 👍.