First off, is it not possible to simply import axios
in the components where it's needed? Using global properties is discouraged in Vue 3 with the composition API. With that said, this is still possible in a few ways:
Importing where needed
The ideal method, as I mentioned earlier, is simply to
import axios from 'axios'
in components where it is needed.
Provide/inject
If, for whatever reason, you do need to provide Axios globally from your app
, another way to do so is to use the Provide/Inject
pattern.
In your App.vue
:
import { provide } from 'vue'
export default {
setup() {
provide('axios', axios);
}
}
And in whatever components need it:
import { inject } from 'vue'
export default {
setup() {
const axios = inject('axios');
}
}
getCurrentInstance()
(discouraged)
Per the Vue documentation,
Usage of getCurrentInstance
is strongly discouraged in application code. Do NOT use it as an escape hatch to get the equivalent of this in Composition API.
However, if you really want to maintain it as a global property, you can use it as follows:
import { getCurrentInstance } from 'vue';
export default {
setup() {
const app = getCurrentInstance();
const axios = app.appContext.config.globalProperties.$http;
$http
but why don't you import it in the component? β Phosphor