24

I created a new project using:

vue create hello-world

Generating a new project that includes the HelloWorld.vue, app.vue, main.js (etc ...) files.

Now I install Axios by following the docs Npm vue-axios:

npm install --save axios vue-axios

I import Axios in the main.js file:

import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'

And now I run into a problem that I don't understand. The VueAxios docs say you simply use it like so:

const app = Vue.createApp(...)
app.use(VueAxios, axios)

But the way app is created in Vue 3 is different. I think this is where the problem comes from:

createApp(App).mount('#app')

So, how do I correctly import axios?

Boussadjra Brahim
  • 82,684
  • 19
  • 144
  • 164
RDU
  • 812
  • 1
  • 9
  • 22

3 Answers3

51

createApp(App).mount('#app') is effectively the same as:

import Vue from 'vue'
const app = Vue.createApp(App)
app.mount('#app')

// or
import { createApp } from 'vue'
const app = createApp(App)
app.mount('#app')

So following Vue Axios's docs, just insert the line for app.use():

import { createApp } from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'

const app = createApp(App)
app.use(VueAxios, axios) // 
app.mount('#app')

You could also chain it like this:

createApp(App).use(VueAxios, axios).mount('#app')

demo

tony19
  • 125,647
  • 18
  • 229
  • 307
  • 3
    @RizaKhan Technically, the original question has nothing to do with Composition API (and that tag should probably be removed), so I wouldn't update the demo here. In any case, I would simply import `axios` where needed (including in the Composition API) instead of using `vue-axios`. – tony19 Aug 11 '21 at 02:40
29

You could import only axios and define it as a global property :

Using a bundler (vue cli, vite or webpack ...):

import { createApp } from 'vue'
import axios from 'axios'
const app = createApp(...)
app.config.globalProperties.axios=axios

then use it in any child component like:

Option api :

this.axios.get(...)

in Composition api I recommend to import it directly like :

import axios from 'axios'

const MyComponent = {
  setup() {
    //use axios here

   .... 
  }
}

or you use useAxios from the vueuse (vue composition utilities) :

import { useAxios } from '@vueuse/integrations/useAxios'
...
 setup() {
   const { data, isFinished } = useAxios('/api/posts')
 }
Boussadjra Brahim
  • 82,684
  • 19
  • 144
  • 164
0

This worked for me at VueJS 3.

npm i vue-axios

import { createApp } from "vue";
import axios from 'axios'
import VueAxios from 'vue-axios'

const app = createApp(App);
app.use(VueAxios)
app.use(axios)

app.mount("#app");


this.axios.get(api).then((response) => {
    console.log(response.data)
})

Doc link: https://www.npmjs.com/package/vue-axios

Pri Nce
  • 576
  • 6
  • 18