use axios globally in all my components vue use axios globally in all my components vue vue.js vue.js

use axios globally in all my components vue


In main.js you can just assign Axios to $http.

main.js

import Axios from 'axios'Vue.prototype.$http = Axios;

By modifying the vue prototype, any vue instance will have the ability to call $http on this. (e.g. this.$http.get('https://httpbin.org/get')

Note: $http is the axios object now, so any method you can call on axios object, you can call on this.$http.


For VUE3, you need to add below code:

Syntax:

app.config.globalProperties.{variable} = value;

Example:

app.config.globalProperties.$http = Axios; // Allow axios in all componenets this.$http.get

In your main.js or app.js

/** * Importing libraries & componenets */import { createApp } from 'vue';import { createWebHistory, createRouter } from 'vue-router';import Axios from 'axios';/** * Vue initialization */const app = createApp({    components: {         Index     },});app.use(router);app.config.globalProperties.$http = Axios; // Allow axios in all componenets this.$http.getapp.mount('#app');

You can call the GET method same as VUE2 in your components: this.$http.get('https://httpbin.org/get')