Home » How To Declare A Global Variable in Vue

How To Declare A Global Variable in Vue

Last updated on June 16, 2020 by

Often, most experienced developers declare a global variable so that they can access it throughout the application like a SiteURLs, Database object, paths, etc . So in this article, we will talk about how to declare a global variable in Vue. Are you ready guys? Let’s just go through it.

Table of Contents
1. Declare A Global Variable in VueJS
2. Real-World Examples
3. Accessing Global Variable

Declare A Global Variable in VueJS

As other programming languages, VueJS providing a very cleaner way to declare global variable so that you can make them available for each Vue instance by using the following syntax:

Vue.prototype.$variablename

As per the official document of VueJS: $ is a convention Vue uses for properties that are available to all the instances. This avoids conflicts with any defined data, computed properties, or methods

Real-World Examples

We assume that we all very well familiar with the axios. Axios is used to make HTTP requests like GET, POST, PUT, etc. And we know most of us are include Axios into each Vue component and accessing it but the thing has changed now.

We can now declare it globally and use throughout all the component. Let’s make it globally accessible with the site_url.

Open your app.js file and add the below-highlighted code. Just remember that you should add the code to your main JS file.

// This import can be any in your files
window.Vue = require('vue');
import Vuelidate from 'vuelidate';
import VueRouter from 'vue-router';
import axios from 'axios';

// global variable
Vue.prototype.$axios = axios;
Vue.prototype.$site_url = "https://jsonplaceholder.typicode.com/";

const app = new Vue({
    el: '#app',
    components: { App },
    router
});

Accessing Global Variable

Now, after declaring the variable, we would like to access it. To do go to any Vue component and try to access your global variable like this.$variablename.

<template>
  <div id="app">
    <ul v-for="user in users" :key="user.id">
      <li>{{user.id}}</li>
      <li>{{user.name}}</li>
    </ul>
  </div>
</template>

<script>
export default {
  data: function() {
    return {
      users: []
    };
  },
  created: function() {
    this.$axios.get(this.$site_url + "users")    
    .then(response => {
      this.users = response.data;
    });
  }
};
</script>

That’s it for now. We hope this article helped you to declare a global variable in Vue.

Additionally read our guide on Simple Date formatting in JavaScript.

Please let us know in the comments if everything worked as expected, your issues, or any questions. If you think this article saved your time & money, please do comment, share, like & subscribe. Thank you in advance 🙂. Keep Smiling! Happy Coding!

 
 

Leave a Comment