Declare a Global Variable in Vue.js

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

Syntax

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

Vue.prototype.$variablename

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:

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

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

new Vue({
  render: h => h(App),
}).$mount('#app')

Retrieve the Variables

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

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

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

The tutorial is over. Thank you.


Software Engineer | Ethical Hacker & Cybersecurity...

Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.