Vue.prototype extensions
Introduction
In Vue 2, it's pretty popular, especially in libraries, to extend the prototype of the Vue
constructor in order to make all sorts of stuff available in all components as instance properties.
We no longer have a Vue
constructor, but Vue 3 offers a new wax to add globally available instance properties - we already used it in the previous chapter about filters, so this should be pretty straightforward.
Then, in Vue 2
A common example: making axios, a data fetching library, available in all components.
import Vue from 'vue'
import axios from 'axios'
// ...
Vue.prototype.$axios = axios
Now, in Vue 3
We can make use of app.config.globalProperties
to expose axios to all of your app's components instead of polluting the whole Vue constructor with a prototype extension.
import { createApp } from 'vue'
import axios from 'axios'
const app = createApp(/* ... */)
app.config.globalProperties.$axios = axios
Composition API
If you plan on using the composition API later, it's worth knowing that global properties are not accessible in setup()
.
provide/inject
Rather, you should use provide()
to make content available to child components and actively inject()
it where you need it:
// for components using the normal options API
app.config.globalProperties.$axios = axios
// for components using the Composition API
app.provide('axios', axios)
Then, in a component:
import { inject } from 'vue'
export default {
setup() {
const axios = inject('axios)
}
}
This may seem a bit cumbersome in this simplified example - after all, we could just as well import axios directly!
But it might be advantageous to use this for more involved pieces that you want to make available. It provides a bunch of benefits like easy mocking during tests.