Add global variable in Vue.js 3 Add global variable in Vue.js 3 vue.js vue.js

Add global variable in Vue.js 3


The most direct replacement is app.config.globalProperties. See:

https://v3.vuejs.org/api/application-config.html#globalproperties

So:

Vue.prototype.$myGlobalVariable = globalVariable

becomes:

const app = Vue.createApp({})app.config.globalProperties.$myGlobalVariable = globalVariable

Note that this is scoped to a particular application rather than being global as it was with Vue.prototype. This is by design, all global configuration options are now scoped to an application.

The relevant RFC is here:

https://github.com/vuejs/rfcs/blob/master/active-rfcs/0009-global-api-change.md

Note that application-level provide/inject (also discussed in that RFC) is also an alternative to using Vue.prototype:

const app = Vue.createApp({})app.provide('myGlobalVariable', globalVariable)// In the descendant componentexport default {  inject: ['myGlobalVariable']}

Docs: https://v3.vuejs.org/api/application-api.html#provide

The idea here is that the component can explicitly declare the property rather than inheriting it by magic. That avoids problems like name collisions, so there's no need to use a $ prefix. It can also help to make it clearer where exactly a property is coming from.

Which approach you prefer will depend on your circumstances.


I recommend to use provide/inject approach as follows :

in main.js :

import {createApp} from 'vue'let app=createApp({  provide:{    globalVariable:123  }}).$mount('#app')

in some child or grand-child component do :

export default{ name:'some-compo', inject:['globalVariable'], //then access this.globalVariable as property in you component...}

for composition api and script setup :

 import { inject } from 'vue'  let globalVar=inject('globalVariable')


For those of you who are confused about how to access globalProperties in the setup() method, you can use getCurrentInstance() as in the following documentation.

https://v3.vuejs.org/api/composition-api.html#getcurrentinstance