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:
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:
<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. ?
Comment
Preview may take a few seconds to load.
Markdown Basics
Below you will find some common used markdown syntax. For a deeper dive in Markdown check out this Cheat Sheet
Bold & Italic
Italics *asterisks*
Bold **double asterisks**
Code
Inline Code
`backtick`Code Block```
Three back ticks and then enter your code blocks here.
```
Headers
# This is a Heading 1
## This is a Heading 2
### This is a Heading 3
Quotes
> type a greater than sign and start typing your quote.
Links
You can add links by adding text inside of [] and the link inside of (), like so:
Lists
To add a numbered list you can simply start with a number and a ., like so:
1. The first item in my list
For an unordered list, you can add a dash -, like so:
- The start of my list
Images
You can add images by selecting the image icon, which will upload and add an image to the editor, or you can manually add the image by adding an exclamation !, followed by the alt text inside of [], and the image URL inside of (), like so:
Dividers
To add a divider you can add three dashes or three asterisks:
--- or ***

Comments (0)