How to use Vue.prototype or global variable in Vue 3?
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."
There is a way to use globalProperties
inside a setup function. Although this might be considered an anti-patter. It would be better to use provide/inject if possible. But if there is a library that uses globalProperties and you really need to access it from setup this is how you could do it.
<script setup> import { getCurrentInstance } from 'vue' const app = getCurrentInstance() const progressBar = app.appContext.config.globalProperties.$Progress progressBar.start()</script>