Home > Enterprise >  Vue 3 - global axios instance
Vue 3 - global axios instance

Time:03-08

I want to make an axios instance available globally in my Vue 3 app.

Setup:

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

const axiosInstance = axios.create({
  withCredentials: true,
})

const app = createApp()

app.config.globalProperties.$axios = axiosInstance

app.mount(el)

Usage:

let response = await this.$axios.get('/api/leads')

I get this error:

TypeError: this.$axios.get is not a function

Seems like this.$axios is undefined. I cannot figure out why.

Notes:

  1. I'm using the @vue/compat build of Vue to migrate from Vue 2 to Vue 3. I'm following the official migration guide.
  2. When inspecting this.$axios - I get ƒ wrap() ......

CodePudding user response:

The problem is caused by a known bug, where function properties (the result of axios.create() is actually a function) are bound to the component instance proxy, which inadvertently hides the function's own attached properties (i.e., $axios.get in this case). The PR that fixes the issue has not yet been merged.

A workaround is to convert the axiosInstance (a function) into an object with the spread operator:

const axiosInstance = axios.create({
  withCredentials: true,
})

const app = createApp()
                                                   
  • Related