Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a custom global function using composition api | vue3

In main.js, I set axios as a global function.


//main.js
import { createApp } from 'vue';
import App from './App.vue';
import axios from 'axios';
const app = createApp(App);
app.config.globalProperties.$http = axios;
app.mount('#app');

The thing is how do I call this function in a component using composition api?


<script>
export default {
  setup() {
   //how do I call the `axios` global function?
 };
</script>

like image 927
刘嘉琪 Avatar asked May 01 '26 01:05

刘嘉琪


1 Answers

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;
like image 198
futur Avatar answered May 04 '26 01:05

futur



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!