I'd like to declare a global variable in Vue 3 that can be changed at any time by any component (and by main.js itself) and should be reactive.
My main.js file:
const app = createApp(App);
app.config.globalProperties.$myGlobalVariable = {
content: 'not updated'
};
// simulating something async as an HTTP call
setTimeout(() => {
app.config.globalProperties.$myGlobalVariable.content = 'updated';
console.log(app.config.globalProperties.$myGlobalVariable.content); // updated
}, 2000);
app.mount('#app');
My component file:
<script>
export default {
created() {
setTimeout(() => {
console.log(this.$myGlobalVariable.content)// updated
}, 3000);
}
}
</script>
<template>
<main>
<p>{{ $myGlobalVariable.content }}</p>
</main>
</template>
Inside my component (the p
element), I only see not updated
, although the setTimeout
inside the created()
function of my component proves that it has changed.
How can I get the value of $myGlobalVariable.content
to change inside the p
element?
CodePudding user response:
You're placing a non reactive object into globalProperties
and expect it to become reactive. It won't happen.
Vue exposes its reactivity so it can be imported and used anywhere.
Making $myGlobalVariable
reactive is straight forward and intuitive:
app.config.globalProperties.$myGlobalVariable = reactive({
content: 'not updated'
})
Demo:
const { createApp, reactive } = Vue
const app = createApp()
app.config.globalProperties.$myGlobalVariable = reactive({
content: 'not updated'
})
app.mount('#app')
<script src="https://unpkg.com/[email protected]/dist/vue.global.prod.js"></script>
<div id="app">
<input v-model="$myGlobalVariable.content" />
<pre v-text="$myGlobalVariable" />
</div>