Declare a Global Variable in Vue.js

Published: Nov 11, 2019 - Updated: Jan 24, 2023

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.


No comments yet…