最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - How to expose a variable in app.vue globally in vue.js - Stack Overflow

matteradmin6PV0评论

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.

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.

Share Improve this question asked Jul 24, 2019 at 16:06 SM079SM079 7833 gold badges11 silver badges32 bronze badges 1
  • How do you instantiate your App? Just store the instance in a global variable and access its .gblData property there. – Bergi Commented Jul 24, 2019 at 16:59
Add a ment  | 

3 Answers 3

Reset to default 3

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 ponent like this:

console.log(this.$gblData);

Yes you can pass this variable thhrough window object:

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

in vue3:

// Vue3

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


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

comment list (0)

  1. No comments so far