Answer a question

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>

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;
Logo

Vue社区为您提供最前沿的新闻资讯和知识内容

更多推荐