Home » How To Declare A Global Variable In Vue

How To Declare A Global Variable In Vue

Last updated on December 30, 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:

  1. How to Select Data Between Two Dates in MySQL
  2. Error After php artisan config:cache In Laravel
  3. Specified Key Was Too Long Error In Laravel
  4. AJAX PHP Post Request With Example
  5. How To Use The Laravel Soft Delete
  6. How To Add Laravel Next Prev Pagination
  7. cURL error 60: SSL certificate problem: unable to get local issuer certificate
  8. Difference Between Factory And Seeders In Laravel
  9. Laravel: Increase Quantity If Product Already Exists In Cart
  10. How To Calculate Age From Birthdate
  11. How to Convert Base64 to Image in PHP
  12. Check If A String Contains A Specific Word In PHP
  13. Dynamically Populate A Select Field’s Choices In ACF
  14. How To Find Duplicate Records in Database
  15. Angular DataTable Tutorial With Example

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

*

code