Search code examples
vue.jsglobal-variablesvuejs3

Set global variables in vue 3


As u will see in the code, i am following vue 3 documentation on how to use global variables in vue 3, https://vuejs.org/api/application.html. This is main.js file:

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import 'bootstrap/dist/css/bootstrap.css';
import 'jquery/src/jquery.js'

let app = createApp(App)

/* GLOBAL VARIABLES*/
// app.config.globalProperties.$headingMain = 'Direct mail marketing that works'
app.provide('headingMain', 'Direct mail marketing that works')


createApp(App).use(router).mount('#app')

import 'bootstrap/dist/js/bootstrap.js'

Home.vue component:

<template>
  <h1 class="heading">{{ myHeading }}</h1>
</template>

<script>
export default {
  inject: ["headingMain"],
  data() {
    return {
      myHeading: this.headingMain,
    };
  },
};
</script>

h1 element wont show here. This is approach with app.provide and inject. I also tried with app.config.globalProperties, you can see there is a commented line in main.js


Solution

  • The problem is you have two application instances, and you used provide on one instance while inject-ing from the other instance's child component. The two instances are not connected in any way.

    // app instance 1
    let app = createApp(App)
    app.provide('headingMain', 'Direct mail marketing that works')
    
    // app instance 2 (where the `inject` occurs)
    createApp(App).use(router).mount('#app')
    

    Solution

    Use the same application instance to provide and inject:

    let app = createApp(App)
    app.provide('headingMain', 'Direct mail marketing that works')
    
     👇
    app.use(router).mount('#app')
    

    demo