Md Obydullah Follow I'm Md Obydullah. I build open-source projects and write about Laravel, Linux server, modern JavaScript and web development.

Declare a Global Variable in Vue.js

Published on November 11, 2019 46 sec read

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. 🙂

You're welcome to suggest any article to write!

Md Obydullah Follow I'm Md Obydullah. I build open-source projects and write about Laravel, Linux server, modern JavaScript and web development.

Leave a Reply

Your email address will not be published. Required fields are marked *