SM079
SM079

Reputation: 755

How to expose a variable in app.vue globally in vue.js

I am using vuejs to develop a module of my application, i will be getting data which i need to set to a variable ex this.gblData in the App.vue.

I will build the vue application and integrating it into a another application. Is there a way to expose the variable gblData in the parent application.

Upvotes: 2

Views: 6058

Answers (3)

iraj jelodari
iraj jelodari

Reputation: 3376

in vue3:

// Vue3

const app = Vue.createApp({})
app.config.globalProperties.gblData = 'something'


app.component('a-child-component', {
  mounted() {
    console.log(this.gblData) // 'something'
  }
})

Upvotes: 0

sdn404
sdn404

Reputation: 624

Option 1: Create a global variable

const gblData = "something";

expose your global variable:

new Vue({
    data:{
        gblData
    }
})

Option2: Define global variable in the prototype.

Vue.prototype.$gblData = "something";

you can now use this variable in any vue component like this:

console.log(this.$gblData);

Upvotes: 3

Andrew Vasylchuk
Andrew Vasylchuk

Reputation: 4779

Yes you can pass this variable thhrough window object:

// set
window.gblData = "something";
// get
console.log(window.gblData);

Upvotes: 0

Related Questions