Declare a Global Variable in Vue.js

Last modified on December 17, 2019 45 sec read

In this guide, we are going to learn how to define a global variable in Vue.js.


This is the syntax of declaring a global variable in Vue.js:


Declare a Variable

We are defining two global variables in this tutorial. One is $api_url and another is $axios to make HTTP requests in all components.

Open main.js and declare the variables like this:

import App from './App.vue'
import axios from 'axios'

//global variable
Vue.prototype.$axios = axios
Vue.prototype.$api_url = ""

new Vue({
  render: h => h(App),

Retrieve the Variables

Now we can use the variables in all components. Here’s an example:

<div id="app">
    <ul v-for="user in users" :key="">

export default {
  data: function() {
    return {
      users: []
  created: function() {
    this.$axios.get(this.$api_url + "users")
    .then(res => {
      this.users =;
The tutorial is over. Thank you. 🙂

Monthly Newsletter

One email a month, packed with the latest tutorials, delivered straight to your inbox.
We'll never send any spam or promotional emails.

Hey, I'm Md Obydullah. I build open-source projects and write article on Laravel, Linux server, modern JavaScript and more on web development.


One Reply to “Declare a Global Variable in Vue.js”

Leave a Reply