You could use provide
/inject
or define a global config property, which replaces Vue.prototype
in Vue 3:
1. provide
/inject
(for Composition or Options API)
Provide
import axios from 'axios';
const app = Vue.createApp(App);
app.provide('$axios', axios); // Providing to all components during app creation
Inject
Composition API:
const { inject } = Vue;
...
setup() {
const $axios = inject('$axios'); // injecting in a component that wants it
// $axios.get(...)
}
Options API:
inject: ['$axios'], // injecting in a component that wants it
2. Global config (for Options API)
import axios from 'axios';
const app = Vue.createApp(App);
app.config.globalProperties.$axios = axios;
Options API:
this.$axios
Note: This is only for the Options API. Evan You (Vue creator) says: “config.globalProperties
are meant as an escape hatch for replicating the behavior of Vue.prototype
. In setup
functions, simply import what you need or explicitly use provide
/inject
to expose properties to app.“