Edin Osmic
Edin Osmic

Reputation: 446

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

Upvotes: 1

Views: 10328

Answers (2)

meet vaghsiya
meet vaghsiya

Reputation: 230

// 1. Assign app to a variable
let app = createApp(App)

// 2. Assign the global variable before mounting. (here $globalVar is the name of your global variable. you should use the global name that starts with the '$' sign. but it's not compulsory.)
app.config.globalProperties.$globalVar = 'globalVar'

// 3. Use router and mount app
app.use(router).mount('#app')
  1. if you want to use it in the script then in your component.
 <script>
     export default {
         data() {
             return {
                 myVar: this.$globalVar
             }
         }
     }
 </script>
  1. if you want direcly in template than use like,
 <template>
      <h1>{{ $globalVar }}</h1>
 </template>

Upvotes: 3

tony19
tony19

Reputation: 138696

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

Upvotes: 1

Related Questions