7

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() ......
0

1 Answer 1

8

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()
                                        👇
app.config.globalProperties.$axios = { ...axiosInstance }

demo

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.