Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use axios globally in all my components vue

I am testing with axios within a Vue application and the CLI. I've been using vue-resource and I could access it on all my components by simply passing it to Vue.use (VueResource). How can I achieve this with axios, so I do not have to import it into a component, but simply define it once in the main.js file?

like image 679
FeRcHo Avatar asked Feb 06 '18 19:02

FeRcHo


People also ask

Can I install Axios globally?

P.A They can be anywhere you want. If you didn't want to clutter main. js just put the statements into a lib/axios. js file or something and add all your interceptors, and then export the axios object, and you can assign it in main.

How do I use global component in Vue?

When we want to globally register a component in Vue, we need to do it in this file. All you have to do is import your component, as you usually would, and then register it using app. component . import { createApp } from 'vue' import App from './App.


2 Answers

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.

like image 104
Brandon Deo Avatar answered Sep 20 '22 15:09

Brandon Deo


NOTE: When Vue module is installed as a package and not using through CDN then this approach works fine else if importing Vue from CDN then we have both options, first the answer here and second is to import Vue in main.js and then use Vue.prototype.{variable}=Axios

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.get app.mount('#app'); 

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

like image 39
Mayank Dudakiya Avatar answered Sep 18 '22 15:09

Mayank Dudakiya