[Vuejs]-Set global variables in vue 3

1👍

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

👤tony19

2👍

// 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>

Leave a comment