Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access global variable in vue 3 outside vue component?

I defined my global variable in main.js file like this


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

and then when I tried to access this variable $myGlobalVariable in other js file it is undefined, but I can access in vue components.

In the vue 2 it is possible to access both in js file and vue components. I hope you gonna help me :)

like image 338
Natnael Liza Avatar asked Sep 05 '25 03:09

Natnael Liza


1 Answers

In order to access a global Vue variable outside of a Vue component you have to:

1. Export the app instance

/* main.js */

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

2. Import the app instance in the other JS file

/* other.js */

import { app } from '@/main.js'
console.log(app.config.globalProperties.$myGlobalVariable)
like image 116
GR0ZA Avatar answered Sep 08 '25 14:09

GR0ZA