Skip to content Skip to sidebar Skip to footer

How To Correctly Import Axios In Vue 3 After Creating New Project With Cli?

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

Solution 1:

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

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

// orimport { 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'importVueAxiosfrom'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

Solution 2:

You could import only axios and define 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(...)

Composition api :

import { getCurrentInstance } from'vue'constMyComponent = {
  setup() {
    const internalInstance = getCurrentInstance()

    const axios =internalInstance.appContext.config.globalProperties.axios;

   .... 
  }
}

Post a Comment for "How To Correctly Import Axios In Vue 3 After Creating New Project With Cli?"