Home > OS >  Cant access global variable in Vue 3 and Vite
Cant access global variable in Vue 3 and Vite

Time:11-29

I have this App.js

import './bootstrap';
import { createApp } from 'vue';
import { createRouter, createWebHistory } from 'vue-router';


const app = createApp({});

app.config.globalProperties.$globalVar = 'globa11lVar'

import ExampleComponent from './components/ExampleComponent.vue';
import ExampleComponent2 from './components/ExampleComponent2.vue';

const routes = [
    { path: '/', component: ExampleComponent },
    { path: '/about', component: ExampleComponent2 },
]

const router = createRouter({
.....
});

app.use(router);

app.mount('#app');

as you can see I have app.config.globalProperties.$globalVar to pass the variable.

On my ExampleComponent

<script setup>
import { ref, onMounted, watch } from 'vue'

// lifecycle hooks
onMounted(() => {
   console.log( app.config.globalProperties ); 
})

</script>

Im getting this error

Uncaught (in promise) TypeError: can't access property "globalProperties", app.config is undefined

Any help would be appreciated.

CodePudding user response:

You could achieve that by using getCurrentInstance, but it's not a recommended way, you could use inject/provide to do the same thing :

app.provide('globalVar', 'some globalVar')

in your component :

<script setup>
import { ref, onMounted, watch, inject } from 'vue'

const globalVar = inject('globalVar')

// lifecycle hooks
onMounted(() => {
   console.log( globalVar ); 
})

</script>
  • Related