In main.js
I have something like this:
import { myUtilFunc} from \'./helpers\';
Object.defineProperty(Vue.prototype, \'$myUtilFunc\', { value: m
provide
/inject
Provide
const app = createApp(App);
app.provide('someVarName', someVar); // `Provide` a variable to all components here
Inject:
// In *any* component
const { inject } = Vue;
...
setup() {
const someVar = inject('someVarName'); // injecting variable in setup
}
Note that you don't have to provide from the app root, but can also provide
from any component to only its sub-components:
// In *any* component
setup() {
...
},
provide() {
return {
someVarName: someVar
}
}
[Edit: While my original answer below is still useful for context
properties, it's no longer recommended to use context.root
, which is no longer mentioned in the guide and may soon be deprecated.]
In Vue 3, setup
has an optional second argument for context
. You can access the Vue instance through context.root
instead of this
:
setup(props, context) {
context.root.$myUtilFunc // same as `this.$myUtilFunc` in Vue 2
}
Things you can access through context
:
context.attrs
context.slots
context.parent
context.root
context.emit